Reputation: 51937
I have an with several properties:
MyModel{
public int var1 {get;set;}
public int var2 {get;set;}
public int TheIndex {get;set;}
}
I use this model to populate a list:
var Output = .... select new MyModel {... TheIndex = 0, ...};
Then, I want to fill the index of each element with:
int index = 0;
foreach (var a in Output) { a.TheIndex = index++; }
However, I'm baffled to figure out why it's not adding the index like I think it should. Instead, it's stuck at 0 across the entire collection.
Any ideas?
Thanks.
Upvotes: 1
Views: 327
Reputation: 113412
It is adding the index. The issue is that you are mutating objects streamed out by a query. I'm guessing that you are subsequently re-executing the query and expecting those mutations to have somehow been 'persisted' into the query in a manner that will be reflected in the new results of the query. LINQ queries don't work that way : the result of a query expression is a query, not the results of the query. Every time you enumerate the results, the query runs again. In your case, new instances of MyModel
will be created again, so the changes performed on the old ones are lost.
A few possible fixes:
ToList()
call), and then mutate the elements of the collection.foreach
loop rather than by re-executing the query after the loop.Upvotes: 4
Reputation: 16938
I'm not sure exactly what you mean by "not adding the index like I think it should" however I'd point out that there is a Select extension method that would do what you want in one operation. So
var Output = .... select new MyModel { ... TheIndex = 0, ...};
would become
var Output = (....).Select((elem, idx) => new MyModel { ... TheIndex = idx, ... });
Upvotes: 0