2010-10-21 46 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() 
} 

是指数

相关问题