简体   繁体   English

从 linq 查询返回 ObservableCollection

[英]Return ObservableCollection from linq query

I have following linq snippet我有以下 linq 片段

Note -> This is Metro App, and ICollectionView does not work as expected for grouping/sorting.注意-> 这是 Metro 应用程序,并且ICollectionView无法按预期进行分组/排序。

        ObservableCollection<int> ints = new ObservableCollection<int>();
        ints.Add(3);
        ints.Add(4);
        ints.Add(5);
        ints.Add(6);
        ints.Add(3);
        ints.Add(4);
        ints.Add(1);
        ints.Add(2);


        var groupedInts = ints.GroupBy(i=>i).Select(i=>  new {Key=i.Key, Count=i.Count()});

I want following我想跟随

  1. To subscribe to groupedInts or ObservableCollection corresponding to it (basically databinding from WPF/Metro UI to groupInts)订阅与其对应的 groupedInts 或 ObservableCollection(基本上是从 WPF/Metro UI 到 groupInts 的数据绑定)

  2. Any change in ints (original observablecollection) should be reflected by groupedInts (so that UI subscribing to groupInts/related ObservableCollection can show the changes). ints(原始 observablecollection)的任何变化都应该由 groupedInts 反映(以便订阅 groupInts/相关 ObservableCollection 的 UI 可以显示更改)。

In actual scenario, the data structure is slightly complex (6-7 properties), but the problem boils down to above described issue.在实际场景中,数据结构稍微复杂(6-7个属性),但问题归结为上述问题。

处理ints.CollectionChanged事件并使用相同的 LINQ 查询刷新groupedInts变量...

There's two ways I can think of.我能想到的有两种方法。

1st : Use Bindable Linq / Continuous Linq第一:使用可绑定Linq/连续Linq

2nd : Create a seperate CollectionView for the groupedInts.第二:为 groupedInts 创建一个单独的 CollectionView。 When the original collection changes, this should change along with it.当原始集合更改时,这应该随之更改。 Here's a nice and neat tutorial 这是一个漂亮而整洁的教程

AngelWPFs idea of Notifying the LINQ property as changed is viable, too. AngelWPFs 通知 LINQ 属性更改的想法也是可行的。

You need my ObservableComputations library.你需要我的ObservableComputations库。 Using this library you can code like this:使用这个库,你可以这样编码:

ObservableCollection<int> ints = new ObservableCollection<int>();

ints.Add(3);
ints.Add(4);
ints.Add(5);
ints.Add(6);
ints.Add(3);
ints.Add(4);
ints.Add(1);
ints.Add(2);

var groupedInts = ints.Grouping(i=>i).Selecting(ig =>  new {Key=ig.Key, Count=ig.Count});

groupedInts is ObservableCollection and reflects all the changes in the ints collection. groupedInts 是ObservableCollection并反映了 ints 集合中的所有变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM