c# - Strange behaviour: Added object to ObservableCollection -
i'm having strange behavior when adding object observablecollection , looking it. after adding found , same code isn't anymore?
public class testclass { public testclass(string s) { str = s; } public string str { get; set; } } private observablecollection<testclass> testcollection = new observablecollection<testclass>(); private list<string> newvaluelist = new list<string> { "one", "two", "three" }; private void test() { var tmplist = newvaluelist.select(p => new testclass(p)); foreach (var v in tmplist) { testcollection.add(v); if (testcollection.contains(v)) console.writeline("yes"); else console.writeline("no"); } foreach (var v in tmplist) { if (testcollection.contains(v)) console.writeline("in"); else console.writeline("out"); } }
running code result in output: yes yes yes out out out
when using .tolist()
tmplist
expected result.
select method returns ienumerable object calls getenumerator whenever used in loop hence calling lambda in select method on every element in list seprately both loops.
loop1: select(p => new testclass(p)) loop2: select(p => new testclass(p))
so whenever loop uses tmplist both loops select statement executed calls lambda
hence creating distinct set of objects every loop.
you can verify behaviour creating breakpoint in lambda expression.
you see called 6 times not 3.
Comments
Post a Comment