2013-05-02 42 views
0

我有一個數組S [],我用它設置:瞭解foreach循環序列號

string [] s; 
    s = data.Split(','); 

後,我可以得到從s元素用foreach:

foreach (string c in s) 
        { 
         list.Items.Add(c); 
        } 

但我想寫C的seqeunce接近C值,即它會在列表中顯示:

0 hello 
1 world 
2 earth 

我沒有在使用的foreach一個計數器,有另一種方式?

+0

你想在集合中顯示其索引? – Matthew 2013-05-02 14:55:10

+0

我該怎麼辦 – user2331187 2013-05-02 14:56:19

回答

3

您必須使用計數器。您可以在foreach中使用一個循環,或使用for循環並使用其計數器。

編輯:那麼,如果你開始對空列表您使用list.Items.Count在循環輸出項目的當前計數列表雖然這是真的一個好辦法做到這一點。

// ugly 
foreach (string c in s) 
{ 
    list.Items.Add(list.Items.Count + " " + c); 
} 
+0

你可以舉一個例子用代碼 – user2331187 2013-05-02 14:59:41

+0

更新了答案 – 2013-05-02 15:01:48

+0

我買了你的時間謝謝。 – user2331187 2013-05-02 15:04:02

0

不,沒有其他方式給定您的代碼。

要麼你這樣做:

string [] s= {"0 Hello","1 World", "2 earth"}; 
//your simple foreach loop 

或你這樣做:

int counter=0; 
foreach (string c in s) 
{ 
    list.Items.Add(counter++ + " " + c); 
} 

或更改您的代碼,使用for循環

foreach (int i=0;i<s.Length;i++) 
{ 
    list.Items.Add(i + " " + c[i]); 
} 
+0

Thanks.But我不會使用計數器 – user2331187 2013-05-02 14:57:36

+0

然後使用forloop – 2013-05-02 14:59:18

3

最明顯的事情是將使用常規循環:

for (int i = 0; i < c.Length; i++) { 
    list.Items.Add(i.ToString() + " " + c[i]); 
} 

如果你絕對要使用foreach且無計數器變量,你可以使用Select捆綁每個字符串,其指數:

foreach (var c in s.Select((str, i) => new { Value = str, Index = i })) { 
    list.Items.Add(c.Index.ToString() + " " + c.Value); 
}