Archive for tag: LINQ

Simple Solution for ToObservableCollection() for LINQ Queries

When working with Windows Presentation Foundation and MVVM, you will have to deal a lot with ObservableCollections. And if you also love LINQ, like I do, you will soon come over a very annoying limitation:

LINQ queries always return an IEnumerable which can be very easily "converted" to a generic List:

var result = from x in y
             select x;

return result.ToList();

Sadly, there isn't anything like ToList() for an generic Observable Collection - something like ToObservableCollection() as you might expect.

Luckily, there is such cool stuff like Extension Methods in .NET and it is very easy for us to extend the type IEnumerable with an ToObservableCollection() method that just works as simple as ToList():

public static ObservableCollection<TSource> ToObservableCollection<TSource>
    (this IEnumerable<TSource> source)
{
    ObservableCollection<TSource> collection = 
        new ObservableCollection<TSource>();

    if (source != null)
    {
        foreach (var item in source)
            collection.Add(item);
    }
    else
        collection = null;

    return collection;
}

Just put this class into your project and IEnumerable will be extended with this method immediately. Now we can write:

var result = from x in y
             select x;

return result.ToObservableCollection();

If this doesn't work for you, just make sure that you put this class in the same namespace where you want to use this extension method (or that you import this namespace).