3 回答

TA貢獻1900條經驗 獲得超5個贊
您可以使用LINQ Concat和ToList方法:
var allProducts = productCollection1.Concat(productCollection2)
.Concat(productCollection3)
.ToList();
請注意,有更有效的方法可以執行此操作-上面的操作基本上會遍歷所有條目,從而創建動態大小的緩沖區。正如您可以預測的開始大小一樣,您不需要此動態大小調整...因此您可以使用:
var allProducts = new List<Product>(productCollection1.Count +
productCollection2.Count +
productCollection3.Count);
allProducts.AddRange(productCollection1);
allProducts.AddRange(productCollection2);
allProducts.AddRange(productCollection3);
(為了提高效率AddRange而特例ICollection<T>。)
除非您確實需要,否則我不會采用這種方法。

TA貢獻1946條經驗 獲得超3個贊
假設您想要一個包含指定類別ID的所有產品的列表,則可以將查詢視為投影,然后進行展平操作。還有,做一個LINQ經營者:SelectMany。
// implicitly List<Product>
var products = new[] { CategoryId1, CategoryId2, CategoryId3 }
.SelectMany(id => GetAllProducts(id))
.ToList();
在C#4中,可以將SelectMany縮短為: .SelectMany(GetAllProducts)
如果您已經有代表每個ID的產品的列表,那么您需要的是串聯,正如其他人指出的那樣。

TA貢獻1797條經驗 獲得超4個贊
您可以使用LINQ將它們結合起來:
list = list1.Concat(list2).Concat(list3).ToList();
不過,較傳統的使用方法List.AddRange()可能會更有效。
- 3 回答
- 0 關注
- 2409 瀏覽
添加回答
舉報