2011-08-25 77 views
5

假設:LINQ投影元素計數

var a = SomeCollection.OrderBy(...) 
       .Select(f => new MyType 
           { 
            counter = ? //I want counter value, so what first 
               //object have counter=1, second counter=2 
               //and so on 
            a=f.sometthing, 
            ... 
           }); 

如何設置這個計數器值?或者我是否會在事後迭代a

回答

8

使用Select的過載,它爲您提供當前元素的基於0的索引。

.Select((item, index) => new MyType 
      { 
       counter = index + 1, 
       a = item.Something 
+1

此重載記錄在http://msdn.microsoft.com/en-us/library/bb534869.aspx – Reddog

+0

@Reddog,謝謝,我已經添加了答案的鏈接。 –

+0

這不適用於實體的linq,儘管 – ren

3

只需捕獲變量:

int index = 1; 

var a = SomeCollection.OrderBy(...) 
     .Select(x => new MyType { counter = index++; }); 

計數器計數爲每個迭代被調用。

+0

這不適用於實體的linq – ren