2013-10-03 54 views
0

我有一個字符串合併和追加在列表<string> C#.NET元素

List<string> myList = new List<string>(); 

myList.Add(string1_1); 
myList.Add(string1_2); 
myList.Add(string2_1); 
myList.Add(string2_2); 
myList.Add(string3_1); 
myList.Add(string3_2); 

的列表現在,一些魔術後,我想將列表中的元素結合起來,使它們像這樣

myList[0] = string1_1 + string1_2 
myList[1] = string2_1 + string2_2 
myList[2] = string3_1 + string3_2 

因此也將列表的大小減半。這怎麼能實現?

回答

6

一個簡單的for循環將工作:

List<string> inputList = new List<string>(); 
List<string> outputList = new List<string>(); 

for (int i = 0; i < inputList.Count; i += 2) // assumes an even number of elements 
{ 
    if (i == inputList.Count - 1) 
     outputList.Add(inputList[i]); // add single value 
     // OR use the continue or break keyword to do nothing if you want to ignore the uneven value. 
    else 
     outputList.Add(inputList[i] + inputList[i+1]); // add two values as a concatenated string 
} 

For循環是良好的循環和處理在同一時間對或元素的三胞胎。

+0

看看我的回答,它的工作原理也與不平名單。 – Flea777

+2

LINQ應該讓事情更容易閱讀和更簡潔,不會更混亂和冗長。 –

+0

你也可以添加檢查當我== inputList.Count - 1,如果是的話只添加inputList [i]。但誰知道這是否可以接受的OP的場景...... – Xiaofu

1

你可以嘗試這樣的事:

var half = myList 
      .Select((s,idx) => s + (idx < myList.Count() - 1 ? myList[idx +1] : string.Empty)) 
      .Where((s,idx) => idx % 2 == 0) 
      .ToList(); 

可以在格式字符串[我] +字符串做的所有項目的投影[I + 1](注意要檢查字符串[我+1]的元素存在):

.Select((s,idx) => s + (idx < myList.Count() - 1 ? myList[idx +1] : string.Empty)) 

然後過濾只有偶數元素:

.Where((s,idx) => idx % 2 == 0) 
+1

哇,這很難看...請仔細解釋它的更多細節? – Default

+0

當然。首先做一個投影加入每一對物品。然後只過濾奇數項目。 – Flea777

+0

答案左下方有一個編輯按鈕。我可能會建議你將這個解釋加入你的答案而不是評論中? – Default

6

我肯定會與去for循環方式由Trevor提供的,但如果你想使用LINQ做到這一點,你可以使用GroupBystring.Join

myList = myList.Select((x, i) => new { x, i }) 
       .GroupBy(x => x.i/2) 
       .Select(g => string.Join("", g.Select(x => x.x))) 
       .ToList();