IEnumerable을 ObservableCollection로 변환하는 방법?


130

어떻게 변환하기 IEnumerableObservableCollection?

답변:


209

당으로 MSDN

var myObservableCollection = new ObservableCollection<YourType>(myIEnumerable);

이것은 현재 IEnumerable의 얕은 복사본을 만들어 ObservableCollection으로 만듭니다.


ForEach 루프를 사용하여 항목을 하나씩 컬렉션에 삽입하는 것보다 빠릅니까?
Rexxo

4
@Rexxo 생성자와 함께하는 것이 약간 빠릅니다. 내부적으로을 사용foreach 하면 foreach 문을하고 전화를하지만 경우, 내부 컬렉션에 항목을 복사하는 Add 그것을 통해 갈 것InsertItem 처음에 약간 느린 원인 채울 때 unessesary입니다 여분의 물건을 많이 수행한다.
Scott Chamberlain

간단하고 가장 좋은 답변
peterincumbria

74
  1. 비 제네릭으로 작업하는 경우 다음과 같이 IEnumerable할 수 있습니다.

    public ObservableCollection<object> Convert(IEnumerable original)
    {
        return new ObservableCollection<object>(original.Cast<object>());
    }
    
  2. generic으로 작업하는 경우 다음과 같이 IEnumerable<T>할 수 있습니다.

    public ObservableCollection<T> Convert<T>(IEnumerable<T> original)
    {
        return new ObservableCollection<T>(original);
    }
    
  3. 비 제네릭으로 작업 IEnumerable하지만 요소 유형을 알고 있다면 다음과 같이 할 수 있습니다.

    public ObservableCollection<T> Convert<T>(IEnumerable original)
    {
        return new ObservableCollection<T>(original.Cast<T>());
    }
    

29

일을 더 단순하게하기 위해 Extension 메서드를 만들 수 있습니다 .

public static class Extensions
{
    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> col)
    {
        return new ObservableCollection<T>(col);
    }
}

그런 다음 모든 IEnumerable에서 메소드를 호출 할 수 있습니다

var lst = new List<object>().ToObservableCollection();

3
ObservableCollection<decimal> distinctPkgIdList = new ObservableCollection<decimal>();
guPackgIds.Distinct().ToList().ForEach(i => distinctPkgIdList.Add(i));

// distinctPkgIdList - ObservableCollection
// guPackgIds.Distinct() - IEnumerable 

1

IEnumerable을 ObservableCollection으로 변환하는 C # 함수

private ObservableCollection<dynamic> IEnumeratorToObservableCollection(IEnumerable source)
    {

        ObservableCollection<dynamic> SourceCollection = new ObservableCollection<dynamic>();

        IEnumerator enumItem = source.GetEnumerator();
        var gType = source.GetType();
        string collectionFullName = gType.FullName;
        Type[] genericTypes = gType.GetGenericArguments();
        string className = genericTypes[0].Name;
        string classFullName = genericTypes[0].FullName;
        string assName = (classFullName.Split('.'))[0];

        // Get the type contained in the name string
        Type type = Type.GetType(classFullName, true);

        // create an instance of that type
        object instance = Activator.CreateInstance(type);
        List<PropertyInfo> oProperty = instance.GetType().GetProperties().ToList();
        while (enumItem.MoveNext())
        {

            Object instanceInner = Activator.CreateInstance(type);
            var x = enumItem.Current;

            foreach (var item in oProperty)
            {
                if (x.GetType().GetProperty(item.Name) != null)
                {
                    var propertyValue = x.GetType().GetProperty(item.Name).GetValue(x, null);
                    if (propertyValue != null)
                    {
                        PropertyInfo prop = type.GetProperty(item.Name);
                        prop.SetValue(instanceInner, propertyValue, null);
                    }
                }
            }

            SourceCollection.Add(instanceInner);
        }

        return SourceCollection;
    }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.