合并两个(或更多)名单为一体,在C#.NET名单、两个、更多、为一体

由网友(孤瘾)分享简介:是否可以使用C#转换两个或多个列表成一个单一的名单,在.NET?例如,公共静态列表<产品> GetAllProducts(INT的categoryId){....}。。。VAR productCollection1 = GetAllProducts(CategoryId1);VAR product...

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

阅读全文

相关推荐

最新文章