Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF LINQ and the ObservableCollection

In my WPF application I'd like to use LINQ as much as possible (especially to avoid foreach). But WPF works a lot with the ObservableCollection, and I can't use LINQ with these kind of collection. What can I do?

like image 496
lamarmora Avatar asked Jul 15 '10 16:07

lamarmora


3 Answers

What makes you think you can't use LINQ with ObservableCollection<T>? It implements Collection<T> so it should be fine.

For example:

using System;
using System.Collections.ObjectModel;
using System.Linq;

class Test
{
    static void Main()
    {
        var collection = new ObservableCollection<int>()
        {
            1, 2, 3, 6, 8, 2, 4, 5, 3
        };

        var query = collection.Where(x => x % 2 == 0);
        foreach (int x in query)
        {
            Console.WriteLine(x);
        }
    }
}
like image 109
Jon Skeet Avatar answered Nov 15 '22 08:11

Jon Skeet


Just for anybody else who may come across this issue with trying to filter an ObservableCollection but find that they can't.

Jon is absolutely correct in that there is no reason why you can't do this but the key thing for a newbie or for someone who has been developing with WPF for a while, is that you need to include the "using System.Linq;" namespace. As you soon as you do this, you can do a ".where" query on your object.

like image 18
Mark P Avatar answered Nov 15 '22 09:11

Mark P


The OP asked especially for the LINQ ".ForEach()" Method, which cannot be used on ObservableCollection< T >, since it's implemented for List< T > only.

There is another SO-Topic, where I found my solution: https://stackoverflow.com/a/200584/2408978

like image 1
dba Avatar answered Nov 15 '22 10:11

dba