Come convertire IEnumerable in ObservableCollection?


130

Come convertire IEnumerablein ObservableCollection?

Risposte:


209

Come da MSDN

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

Questo renderà una copia superficiale dell'attuale IEnumerable e lo trasformerà in ObservableCollection.


È più veloce dell'uso di un ciclo ForEach per inserire gli elementi uno alla volta nella raccolta?
Rexxo,

4
@Rexxo sarà leggermente più veloce farlo con il costruttore. Internamente sta usando aforeach per copiare gli oggetti nella collezione interna, tuttavia se esegui la foreach e lo chiami Add , passerà attraverso ilInsertItem che fa un sacco di cose extra che non sono consapevoli quando si riempie inizialmente causando che sia leggermente più lento.
Scott Chamberlain,

Simples e la migliore risposta
peterincumbria

74
  1. Se lavori con non generici IEnumerablepuoi farlo in questo modo:

    public ObservableCollection<object> Convert(IEnumerable original)
    {
        return new ObservableCollection<object>(original.Cast<object>());
    }
    
  2. Se lavori con un generico IEnumerable<T>puoi farlo in questo modo:

    public ObservableCollection<T> Convert<T>(IEnumerable<T> original)
    {
        return new ObservableCollection<T>(original);
    }
    
  3. Se lavori con non generici IEnumerablema conosci il tipo di elementi, puoi farlo in questo modo:

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

29

Per rendere le cose ancora più semplici è possibile creare un metodo di estensione da esso.

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

Quindi è possibile chiamare il metodo su ogni 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

La funzione C # per convertire IEnumerable in 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;
    }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.