开发者

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

An easy solution would of cource be to modify it 开发者_StackOverflow中文版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. If you change your LINQ query to the following line:

(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. Otherwise, it is evaluated only when necessary. Because you call Count() twice, the query is evaluated twice but on different data.


You encountered one of the pitfalls of LINQ. The variable count in your example isn't the result of a query, it is the query. Every time you change something in the underlying collection, the change will be reflected in subsequent calls.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜