lamarmora
lamarmora

Reputation: 1126

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?

Upvotes: 13

Views: 25319

Answers (4)

Igor Buchelnikov
Igor Buchelnikov

Reputation: 555

You need my ObservableComputations library maybe. That is .NET API designed especially to work with LINQ like queries to ObservableCollection in WPF and other .NET UI frameworks that support binding to INotifyCollectionChanged and INotifyPropertyChanged objects (Xamarin, Blazor).

Upvotes: 0

dba
dba

Reputation: 1175

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

Upvotes: 1

Mark P
Mark P

Reputation: 191

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.

Upvotes: 18

Jon Skeet
Jon Skeet

Reputation: 1500185

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);
        }
    }
}

Upvotes: 14

Related Questions