I defined an Order
class as following:
public class Order
{
public int Id { get; set; }
public string OrdNumber { get; set; }
}
var dict = new Dictionary<int, string>();
dict.Add(1, "ORD1");
dict.Add(2, "ORD2");
var orders = dict.Select(a => new Order { Id = a.Key, OrdNumber = a.Value });
I wrote following code to update Order
number:
foreach (var ord in orders)
{
ord.OrdNumber = ord.OrdNumber "*";
Console.WriteLine(ord.OrdNumber);
}
The code execute as I expect, the output is:
ORD1*
ORD2*
but if I add following foreach
after the foreach
shown above:
foreach (var ord in orders)
{
Console.WriteLine(ord.OrdNumber);
}
the result is:
ORD1
ORD2
The complete code is :
var dict = new Dictionary<int, string>();
dict.Add(1, "ORD1");
dict.Add(2, "ORD2");
var orders = dict.Select(a => new Order { Id = a.Key, OrdNumber = a.Value });
foreach (var ord in orders)
{
ord.OrdNumber = ord.OrdNumber "*";
Console.WriteLine(ord.OrdNumber);
}
foreach (var ord in orders)
{
Console.WriteLine(ord.OrdNumber);
}
and the output is :
ORD1*
ORD2*
ORD1
ORD2
Adding .ToList()
to end of following line:
dict.Select(a => new Order { Id = a.Key, OrdNumber = a.Value })
fixes the problem. The output will now be:
ORD1*
ORD2*
ORD1*
ORD2*
Can anyone explain why this happens?
CodePudding user response:
.Select()
returns a IEnumerable
, which is a sequence playing, in your case, a => new Order { Id = a.Key, OrdNumber = a.Value }
Every time you'll foreach
the IEnumerable
, you'll play that sequence.
Now, when adding .ToList()
it materialize the sequence in a List, by creating and keeping the objects. When you foreach
the List, you don't play its creation sequence, but what its values actually hold, that's why in that case ord.OrdNumber = ord.OrdNumber "*";
is keps when using a List