3 回答

TA貢獻1900條經(jīng)驗 獲得超5個贊
您可以使用LINQ Concat和ToList方法:
var allProducts = productCollection1.Concat(productCollection2)
.Concat(productCollection3)
.ToList();
請注意,有更有效的方法可以執(zhí)行此操作-上面的操作基本上會遍歷所有條目,從而創(chuàng)建動態(tài)大小的緩沖區(qū)。正如您可以預測的開始大小一樣,您不需要此動態(tài)大小調(diào)整...因此您可以使用:
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條經(jīng)驗 獲得超3個贊
假設您想要一個包含指定類別ID的所有產(chǎn)品的列表,則可以將查詢視為投影,然后進行展平操作。還有,做一個LINQ經(jīng)營者:SelectMany。
// implicitly List<Product>
var products = new[] { CategoryId1, CategoryId2, CategoryId3 }
.SelectMany(id => GetAllProducts(id))
.ToList();
在C#4中,可以將SelectMany縮短為: .SelectMany(GetAllProducts)
如果您已經(jīng)有代表每個ID的產(chǎn)品的列表,那么您需要的是串聯(lián),正如其他人指出的那樣。

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