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

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

问题描述

是否可以使用C#转换两个或多个列表成一个单一的名单,在.NET?

例如,

 公共静态列表<产品> GetAllProducts(INT的categoryId){....}
。
。
。
VAR productCollection1 = GetAllProducts(CategoryId1);
VAR productCollection2 = GetAllProducts(CategoryId2);
VAR productCollection3 = GetAllProducts(CategoryId3);
 

解决方案

您可以使用LINQ Concat的 了ToList 方法:

  VAR allProducts = productCollection1.Concat(productCollection2)
                                    .Concat(productCollection3)
                                    .ToList();
 

请注意,有更有效的方法来做到这一点 - 上面基本上都会遍历所有条目,创建动态大小的缓冲区。正如你可以predict开始与大小,你不需要这个动态调整大小...所以你的可以的使用:

  VAR allProducts =新的名单,其中,产品>(productCollection1.Count +
                                    productCollection2.Count +
                                    productCollection3.Count);
allProducts.AddRange(productCollection1);
allProducts.AddRange(productCollection2);
allProducts.AddRange(productCollection3);
 

的AddRange 是特例,对于的ICollection< T> 为了提高效率)

我不会采取这种方法,除非你真的要,但。

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

For example,

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

解决方案

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 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天全站免登陆