Answers:
根据MSDN
var myObservableCollection = new ObservableCollection<YourType>(myIEnumerable);
这将对当前IEnumerable进行浅表复制,并将其放入ObservableCollection中。
foreach来将项目复制到内部集合中,但是,如果您进行了foreach并调用Add 它,则会进行InsertItem很多额外的工作,这些工作在最初填充时是不必要的,从而导致其速度稍慢。
如果您使用的是非泛型IEnumerable,则可以这样进行:
public ObservableCollection<object> Convert(IEnumerable original)
{
return new ObservableCollection<object>(original.Cast<object>());
}如果您使用的是泛型IEnumerable<T>,则可以通过以下方式进行操作:
public ObservableCollection<T> Convert<T>(IEnumerable<T> original)
{
return new ObservableCollection<T>(original);
}如果您使用非泛型IEnumerable但知道元素的类型,则可以通过以下方式进行操作:
public ObservableCollection<T> Convert<T>(IEnumerable original)
{
return new ObservableCollection<T>(original.Cast<T>());
}C#函数将IEnumerable转换为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;
}