Item from IEnumerable changed inside foreach, but change not saved to collection

后端 未结 1 1053
眼角桃花
眼角桃花 2021-01-14 13:27

I had an interesting problem today, this is a reproduction:

class TestListAndEnumerable
{
    public static void Test()
    {
        bool b1 = GetBool1(); /         


        
相关标签:
1条回答
  • 2021-01-14 13:47

    This is a matter of LINQ's lazy evaluation. Each time you iterate over list in GetBool1(), you're creating a new sequence of values. Changing the Value property in one of those objects doesn't change anything else.

    Compare that with GetBool2(), where you're got a call to ToList(), which means you're creating a List<T> with a sequence of objects in. Now each time you iterate over that list, you'll get references to the same objects... so if you modify the value within one of those objects, you'll see that next time.

    If you change your Select argument to

    x => { Console.WriteLine("Selecting!"); return new BoolContainer { Value = x } };

    ... then add appropriate extra Console.WriteLine calls so you can see when it's taking place, you'll see that the delegate is never called in GetBool2() after the call to ToList(), but in GetBool1() it will be called each time you iterate over the sequence.

    0 讨论(0)
提交回复
热议问题