更新时间:2023-02-22 13:05:21
您可以使用 LINQ Concat
和 ToList
方法:
You can use the LINQ Concat
and ToList
methods:
var allProducts = productCollection1.Concat(productCollection2)
.Concat(productCollection3)
.ToList();
请注意,有更有效的方法可以做到这一点 - 上面基本上将遍历所有条目,创建一个动态大小的缓冲区.正如您可以预测开始时的尺寸一样,您不需要这种动态尺寸...所以您可以使用:
Note that there are more efficient ways to do this - the above will basically loop through all the entries, creating a dynamically sized buffer. As you can predict the size to start with, you don't need this dynamic sizing... so you could use:
var allProducts = new List<Product>(productCollection1.Count +
productCollection2.Count +
productCollection3.Count);
allProducts.AddRange(productCollection1);
allProducts.AddRange(productCollection2);
allProducts.AddRange(productCollection3);
(AddRange
是 ICollection
的特殊情况,以提高效率.)
(AddRange
is special-cased for ICollection<T>
for efficiency.)
除非您真的必须这样做,否则我不会采用这种方法.
I wouldn't take this approach unless you really have to though.