Why is my update not persisting?
I have an anonymous type (grps) populated from a linq query. One of the field (DYs) contains an array.
if I run this code:
grps.ElementAt(0).Product = "kkk";
I get a compile error.
If I run this code I get no errors but the value is unchanged.
grps.ElementAt(0).DYs[0] = 19;
Console.WriteLine(grps.ElementAt(0).DYs[0]); // not 19
If, however, I do a foreach on grps and then do a nested step through of each array, I can change the values of the array and they are reported, within the nested loop, as changed. Outside the nested loop they are still unchanged.
I need to make changes to the values in the arrays in my anonymous type but I cannot figure out how.
This has annoyed and confused me because I spent time writing 开发者_如何学运维code that I thought was working ok, but turns out not to without producing any errors.
UPDATE
The upshot to this is that as usual when I have encountered a problem it's because I've forgotten to stick ToList() on the end of something.
Yes, you would get a compile-error for the first one - you're trying to set a property in an anonymous type, and you can't do that in C#. In the second case, you're not trying to set a property - you're just mutating an array. That's an entirely different operation - it's like doing something like:
private readonly StringBuilder builder = new StringBuilder("hello");
...
builder.Append("Stuff");
This changes the contents of the object which builder
refers to; it doesn't change the value of the builder
variable. Anonymous type properties are read-only in the sense that you can't change their values - but if the value is a reference to a mutable object, you can still mutate the object.
Now, in the second form: you're calling ElementAt
twice. That means it will execute the query again the second time - creating a new instance, and thus a new array. The object whose array you changed earlier has gone. However, if you do this:
var list = grps.ToList();
list[0].DYs[0] = 19;
Console.WriteLine(list[0].DYs[0]);
it will print out 19.
Why is my update not persisting?
Unless you used something like .ToList()
on your linq query, you are generating a different sequence with each call to ElementAt(0)
.
The definition of grps
is key here... If it's linq... that's your problem.
why does one compile, but the other not compile?
You are asking for an array .DYs
, and then you are changing part of the array (then throwing the array away.). That's why the second statement compiles, but the first does not.
精彩评论