简体   繁体   English

这是ObservableCollection和Linq的正确行为吗?

[英]Is this the correct behavior of a ObservableCollection and Linq?

Hi I just ran into a sync problem, and have replicated it in this small example. 嗨,我只是遇到了一个同步问题,并在这个小例子中复制了它。

class MyClass
    {
        public int Number { get; set; }
    }

static void Main(string[] args)
        {
            var list = new ObservableCollection<MyClass>
                           {
                               new MyClass() {Number = 1},
                               new MyClass() {Number = 2},
                               new MyClass() {Number = 3}
                           };

            var count = from i in list where i.Number == 1 select i;
            Console.WriteLine("Found {0}", count.Count());

            list[2].Number = 1;
            Console.WriteLine("Found {0}", count.Count());
        }

This will output 这将输出

Found 1
Found 2

This is not what I expected, would have guessed it would return 1 both times. 这不是我所期望的,我猜它会两次都返回1。 It there anyway to avoid this action and still use a observable collection? 无论如何,它会避免执行此操作并仍然使用可观察的集合?

I'm trying to implement a method to reorder, but this makes it hard to select the correct item. 我正在尝试实现一种重新排序的方法,但这很难选择正确的项目。

UPDATE UPDATE

An easy solution would of cource be to modify it like this 一个简单的解决方案很简单,就是像这样修改它

int found = count.Count();
            Console.WriteLine("Found {0}", found);

            list[2].Number = 1;
            Console.WriteLine("Found {0}", found);

This is due to the lazy evaluation of your LINQ query and has nothing to do with the ObservableCollection . 这是由于对LINQ查询的延迟评估,与ObservableCollection没有关系。 If you change your LINQ query to the following line: 如果将LINQ查询更改为以下行:

(from i in list where i.Number == 1 select i).ToList();

you will see the behavior you expect. 您将看到预期的行为。

The ToList() addition makes sure your LINQ query is evaluated at that moment. ToList()附加功能确保此时评估您的LINQ查询。 Otherwise, it is evaluated only when necessary. 否则,仅在必要时进行评估。 Because you call Count() twice, the query is evaluated twice but on different data. 因为您两次调用Count() ,所以该查询被两次评估,但使用的是不同的数据。

You encountered one of the pitfalls of LINQ. 您遇到了LINQ的陷阱之一。 The variable count in your example isn't the result of a query, it is the query. 变量count在你的例子不是一个查询的结果 ,它查询。 Every time you change something in the underlying collection, the change will be reflected in subsequent calls. 每次更改基础集合中的某些内容时,更改都会反映在后续调用中。

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

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