开发者

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 开发者_如何学CObservableCollection, and I can't use LINQ with these kind of collection. What can I do?


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.


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


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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜