Câu trả lời:
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.
foreach
để 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.
Nếu bạn đang làm việc với người không chung chung, IEnumerable
bạn có thể làm theo cách này:
public ObservableCollection<object> Convert(IEnumerable original)
{
return new ObservableCollection<object>(original.Cast<object>());
}
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);
}
Nếu bạn đang làm việc với những người không chung chung IEnumerable
như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>());
}
Để 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();
ObservableCollection<decimal> distinctPkgIdList = new ObservableCollection<decimal>();
guPackgIds.Distinct().ToList().ForEach(i => distinctPkgIdList.Add(i));
// distinctPkgIdList - ObservableCollection
// guPackgIds.Distinct() - IEnumerable
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;
}