As Ekin says, you can write a generic method that turns any IEnumerable<T> into an ObservableCollection<T> . This has one significant advantage over creating a new instance of ObservableCollection using the constructor - the C # compiler is able to automatically call the type parameter when the method is called, so you do not need to write the element type. This allows you to create a collection of anonymous types, which would be impossible (for example, when using the constructor).
One improvement over the Ekin version is to write the method as an extension method. Following the usual naming scheme (e.g. ToList or ToArray ), we can call it ToObservableCollection :
static ObservableCollection<T> ToObservableCollection<T> (this IEnumerable<T> en) { return new ObservableCollection<T>(en); }
Now you can create an observable collection containing anonymous types returned from the LINQ query, for example:
var oc = (from t in visibleTasks where t.IsSomething == true select new { Name = t.TaskName, Whatever = t.Foo } ).ToObservableCollection();
Tomas petricek
source share