且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C# .NET 中将两个(或更多)列表合并为一个

更新时间:2023-02-22 13:05:21

您可以使用 LINQ ConcatToList 方法:

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);

(AddRangeICollection 的特殊情况,以提高效率.)

(AddRange is special-cased for ICollection<T> for efficiency.)

除非您真的必须这样做,否则我不会采用这种方法.

I wouldn't take this approach unless you really have to though.