在 C# .NET 中将两个(或更多)列表合并为一个 [英] Merge two (or more) lists into one, in C# .NET

查看:49
本文介绍了在 C# .NET 中将两个(或更多)列表合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 C# 的 .NET 中,是否可以将两个或多个列表转换为一个列表?

Is it possible to convert two or more lists into one single list, in .NET using C#?

例如

public static List<Product> GetAllProducts(int categoryId){ .... }
.
.
.
var productCollection1 = GetAllProducts(CategoryId1);
var productCollection2 = GetAllProducts(CategoryId2);
var productCollection3 = GetAllProducts(CategoryId3);

推荐答案

您可以使用 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.

这篇关于在 C# .NET 中将两个(或更多)列表合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆