开发者

indexing a collection

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 {... Th开发者_StackOverflow社区eIndex = 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.


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:

  1. Build the appropriate index for each element into the query itself.
  2. Materialize the query into a collection (e.g. with a ToList() call), and then mutate the elements of the collection.
  3. Perform the 'final' necessary side-effect (which you haven't shown us) on each element of the result-sequence inside the foreach loop rather than by re-executing the query after the loop.


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, ... });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜