2010-10-21 45 views
1

在PHP中我可以這樣做:我可以通過foreach訪問索引嗎?

$list = array("element1", "element2"); 
foreach ($list as $index => $value) { 
    // do stuff 
} 

在C#中我可以這樣寫:

var list = new List<string>(){ "element1", "element2" }; 
foreach (var value in list) 
{ 
    // do stuff() 
} 

但我怎麼能在C#版本訪問索引值?

+0

[C#newbie:找出foreach塊中的索引]的可能重複(http://stackoverflow.com/questions/1192447/c-newbie-find-out-the-index-in-a-foreach-塊) – adrianbanks 2010-10-21 09:09:50

+0

這是一個http://stackoverflow.com/questions/521687/c-foreach-with-index的副本,但這個問題的目標受衆是(ex)php程序員而不是Ruby/Python程序員) – 2010-10-21 14:00:53

回答

2

找到多個解決方案上:foreach with index

我很喜歡這兩個JarredPar的解決方案:

foreach (var it in list.Select((x,i) => new { Value = x, Index=i })) 
{ 
    // do stuff (with it.Index)  
} 

和丹·芬奇的解決方案:

list.Each((str, index) => 
{ 
    // do stuff 
}); 

public static void Each<T>(this IEnumerable<T> ie, Action<T, int> action) 
{ 
    var i = 0; 
    foreach (var e in ie) action(e, i++); 
} 

我選擇了丹·芬奇的方法更好的代碼的可讀性。
(我也沒有需要使用continuebreak

+0

Jared's該鏈接的解決方案非常好。 – 2010-10-21 10:53:18

1

我不知道這是可能得到的指數在foreach。只需添加一個新變量i,然後增加它;這很可能是這樣做的最簡單的方法...

int i = 0; 
var list = new List<string>(){ "element1", "element2" }; 
foreach (var value in list) 
{ 
    i++; 
    // do stuff() 
} 
1

如果你有一個List,那麼你可以使用一個索引+ for循環:

var list = new List<string>(){ "element1", "element2" }; 
for (int idx=0; idx<list.Length; idx++) 
{ 
    var value = list[idx]; 
    // do stuff() 
} 
1

如果你想訪問你的索引應該使用循環

for(int i=0; i<list.Count; i++) 
{ 
    //do staff() 
} 

是指數

相關問題