如何将IEnumerable转换为ObservableCollection?

如何将IEnumerable转换为ObservableCollection

根据MSDN

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

这将使当前的IEnumerable的一个浅的副本,并把它变成一个ObservableCollection。

  1. 如果你正在使用非genericsIEnumerable你可以这样做:

     public ObservableCollection<object> Convert(IEnumerable original) { return new ObservableCollection<object>(original.Cast<object>()); } 
  2. 如果你正在使用genericsIEnumerable<T>你可以这样做:

     public ObservableCollection<T> Convert<T>(IEnumerable<T> original) { return new ObservableCollection<T>(original); } 
  3. 如果您使用的是非genericsIEnumerable但知道元素的types,则可以这样做:

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

为了使事情更简单,你可以创build一个扩展方法。

 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(); 
 ObservableCollection<decimal> distinctPkgIdList = new ObservableCollection<decimal>(); guPackgIds.Distinct().ToList().ForEach(i => distinctPkgIdList.Add(i)); // distinctPkgIdList - ObservableCollection // guPackgIds.Distinct() - IEnumerable 

将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; }