我有例如5列出所有相同的類型。我可以簡單地做:列表<T>'X'數量的列表連鎖
List<T> newset = List1.Concat(List2).Concat(List3).Concat(List4).....
我有例如5列出所有相同的類型。我可以簡單地做:列表<T>'X'數量的列表連鎖
List<T> newset = List1.Concat(List2).Concat(List3).Concat(List4).....
你可以,但不要忘了到底追加.ToList();
。 也可以撥打newset.AddRange(ListX);
我認爲這是在性能
是的,你可以做到這一點。
List<Thing> newSet = List1.Concat(List2).Concat(List3).Concat(List4).ToList();
你當然可以做到這一點,儘管它可能不是非常有效。
正如其他答案所述,不要忘記將.ToList()
添加到您的代碼行末尾,或使用List1.AddRange(List2); List1.AddRange(List3); ...
以提高效率。
你可以這樣做(儘管你最後需要.ToList()
)。
但是,生成單個列表會稍微更有效,並使用AddRange添加到每個列表中。只需使用所有列表的總大小初始化列表,然後重複調用AddRange。
你可能要考慮做這樣的事情:
public List<T> ConcatMultiple<T>(this List<T> list, params[] ICollection<T> others)
{
List<T> results = new List<T>(list.Count + others.Sum(i => i.Count));
results.AddRange(list);
foreach(var l in others)
results.AddRange(l);
return results;
}
然後通過呼叫:
List<MyClass> newset = List1.ConcatMultiple(List2, List3, List4);
考慮到它會返回一個全新的列表,並且不會以任何方式影響主列表,看起來有點奇怪,因爲它是特定列表的擴展方法。 – 2010-03-01 17:53:20
@Ilia:對我來說這並不奇怪,因爲根據使用情況,它與Enumerable.Concat沒有任何區別:http://msdn.microsoft.com/en-us/library/bb302894.aspx – 2010-03-01 18:05:21
方面對於變量列表計數更好:
IEnumerable<T> enumerable = Enumerable.Empty<T>();
foreach (List<T> list in [whatever])
enumerable = enumerable.Concat(list);
在最後你可以添加一個「ToList()」如果你想有一個依靠列表:
List<T> list = enumerable.ToList();
但是,這可能並不需要。
...
如果你想連接列表中的任意(先前未知的)號碼,那麼你可能需要連接一系列列表。也許這樣做最簡單的方法是使用SelectMany
操作(或嵌套from
子句在LINQ查詢):
IEnumerable<List<int>> lists = /* get list of lists */;
List<int> result = lists.SelectMany(e => e).ToList();
的SelectMany
操作要求輸入列表中的每個元素的給定功能(這是一個列表),然後連接所有結果列表(列表的輸入列表中的實際列表)。或者使用LINQ查詢語法:
List<int> result = (from l in lists
from e in l select e).ToList();
我相信C#編譯器實際上可能優化這一點,所以它不會遍歷所有的單個元素(和做同樣的事情與上面明確的版本)。如果你有一個已知數量的列表,你當然可以寫的:
List<int> result = (from l in new[] { list1, list2, list3, list4 }
from e in l select e).ToList();
這是不準確的定義爲此你自己的方法,優雅,但它顯示了LINQ查詢語法是多麼強大。
幾乎相同:[優雅的方式合併多個元素集合](http://stackoverflow.com/questions/4493858/elegant-way-to-combine-multiple-collections-of -elements) – nawfal 2015-05-31 10:22:38