2014-04-17 149 views
0

我有一個List<string>,我想識別列表中的第一個或最後一個元素,以便我可以識別與該項目有關的其他函數。Foreach循環中List <>中的第一個或最後一個元素

例如,

foreach (string s in List) 
{ 
    if (List.CurrentItem == (List.Count - 1)) 
    { 
     string newString += s; 
    } 
    else 
    { 
     newString += s + ", "; 
    } 
} 

我該如何去定義List.CurrentItem?在這種情況下,for循環會更好嗎?

回答

0

可以使用計數器這樣

  int counter = 0 ; 
     foreach (string s in List) 
     { 
       if (counter == 0) // this is the first element 
       { 
        string newString += s; 
       } 
       else if(counter == List.Count() - 1) // last item 
       { 
       newString += s + ", "; 
       }else{ 
       // in between 
       } 
       counter++; 
     } 
8

而是利用String.Join

串接指定數組的元素或一個 集合的成員的,使用每一個元素或 構件之間的指定的分隔符。

它簡單得多。

喜歡的東西

 string s = string.Join(", ", new List<string> 
     { 
      "Foo", 
      "Bar" 
     }); 
0

嘗試這樣:

string newString = ""; 

foreach (string s in List) 
{ 
    if(newString != "") 
    newString += ", " + s; 
    else 
    newString += s; 
} 
1

您可以使用基於LINQ的解決方案

例:

var list = new List<String>(); 
list.Add("A"); 
list.Add("B"); 
list.Add("C"); 

String first = list.First(); 
String last = list.Last(); 
List<String> middle_elements = list.Skip(1).Take(list.Count - 2).ToList(); 
+0

如果您的列表只有1個元素會發生什麼? –

+0

這是一個非常特殊的情況,在使用上面的例子之前必須進行預先檢查! –

相關問題