回答:
MSDNに従って
var myObservableCollection = new ObservableCollection<YourType>(myIEnumerable);
これにより、現在のIEnumerableの浅いコピーが作成され、ObservableCollectionになります。
foreach、アイテムを内部コレクションにコピーするためにaを使用していますが、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>());
}
さらに簡単にするために、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();
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;
}