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 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: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 callCount()twice, the query is evaluated twice but on different data.