2010-10-22 43 views
4

我有一個對象的數組/列表/集合/等。出於示例目的,我們假設它只是一個字符串數組/列表/集合/等。C#將元素拆分爲多個元素

我想遍歷數組並根據特定條件拆分某些元素。這全部由我的對象處理。因此,一旦我有要分割的對象索引,分割對象的標準方法是什麼,然後按順序將它重新插入到原始數組中。我會盡量表現出我的意思是使用的是什麼的字符串數組:

string[] str = { "this is an element", "this is another|element", "and the last element"}; 
List<string> new = new List<string>(); 

for (int i = 0; i < str.Length; i++) 
{ 
    if (str[i].Contains("|") 
    { 
      new.AddRange(str[i].Split("|")); 
    } 
    else 
    { 
      new.Add(str[i]); 
    } 
} 

//new = { "this is an element", "this is another", "element", "and the last element"}; 

此代碼的工作和一切,但有一個更好的方式來做到這一點?有沒有一個已知的設計模式,像一個就地數組拆分?

回答

3

對於這個特定的例子,你可以利用SelectMany來獲得你的新陣列。

string[] array = { "this is an element", "this is another|element", "and the last element" }; 
string[] newArray = array.SelectMany(s => s.Split('|')).ToArray(); 
// or List<string> newList = array.SelectMany(s => s.Split('|')).ToList(); 
// or IEnumerable<string> projection = array.SelectMany(s => s.Split('|')); 
+0

我有同樣的想法,但要符合OP的代碼,它應該是ToList()... – 2010-10-22 01:11:08

+0

考慮到這是在他的問題的樣本,我不認爲它很重要。但是我添加了ToList()調用,並將其作爲投影。 – 2010-10-22 01:13:26

+0

謝謝,完美。我並不十分關心ToList的東西。 – Mark 2010-10-22 02:14:27

0

你可以這樣做:

List<string> newStr = str.SelectMany(s => s.Split('|')).ToList();