Làm cách nào để chuyển đổi IEnumerable thành ObservableCollection?


130

Làm thế nào để chuyển đổi IEnumerablesang ObservableCollection?

Câu trả lời:


209

Theo MSDN

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

Điều này sẽ tạo một bản sao nông của IEnumerable hiện tại và biến nó thành một ObservableCollection.


Điều này có nhanh hơn việc sử dụng vòng lặp ForEach để chèn từng mục một vào bộ sưu tập không?
Rexxo

4
@Rexxo sẽ ​​nhanh hơn một chút để làm điều đó với hàm tạo. Trong nội bộ, nó đang sử dụngforeach để sao chép các mục vào bộ sưu tập nội bộ, tuy nhiên nếu bạn thực hiện foreach và gọi Add nó sẽ diễn raInsertItem trong đó có rất nhiều thứ không cần thiết khi ban đầu làm cho nó chậm hơn một chút.
Scott Chamberlain

Đơn giản và câu trả lời hay nhất
peterincumbria

74
  1. Nếu bạn đang làm việc với người không chung chung, IEnumerablebạn có thể làm theo cách này:

    public ObservableCollection<object> Convert(IEnumerable original)
    {
        return new ObservableCollection<object>(original.Cast<object>());
    }
    
  2. Nếu bạn đang làm việc với chung chung, IEnumerable<T>bạn có thể làm theo cách này:

    public ObservableCollection<T> Convert<T>(IEnumerable<T> original)
    {
        return new ObservableCollection<T>(original);
    }
    
  3. Nếu bạn đang làm việc với những người không chung chung IEnumerablenhưng biết loại yếu tố, bạn có thể làm theo cách này:

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

29

Để làm cho mọi thứ đơn giản hơn nữa, bạn có thể tạo một phương thức mở rộng từ nó.

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

Sau đó, bạn có thể gọi phương thức trên mọi 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

Hàm C # để chuyển đổi IEnumerable thành ObservableCollection

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;
    }
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.