是否可以在。net中使用c#将两个或多个列表转换为一个列表?

例如,

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

当前回答

// I would make it a little bit more simple

 var products = new List<List<product>> {item1, item2, item3 }.SelectMany(id => id).ToList();

这样它是一个多维的列表,. selectmany()将它平铺成一个产品的IEnumerable,然后我使用. tolist()方法。

其他回答

如果你有一个空列表,你想合并它与一个填充列表,不要使用Concat,而是使用AddRange。

List<MyT> finalList = new ();

List<MyT> list = new List<MyT>() { a = 1, b = 2, c = 3 };

finalList.AddRange(list);

你可以使用LINQ将它们组合起来:

  list = list1.Concat(list2).Concat(list3).ToList();

使用List.AddRange()这种更传统的方法可能更有效。

假设您想要一个包含指定类别id的所有产品的列表,您可以将查询视为一个投影,然后是一个扁平化操作。有一个LINQ操作符做这个:SelectMany。

// implicitly List<Product>
var products = new[] { CategoryId1, CategoryId2, CategoryId3 }
                     .SelectMany(id => GetAllProducts(id))
                     .ToList();

在c# 4中,你可以将SelectMany缩短为:.SelectMany(GetAllProducts)

如果您已经拥有代表每个Id的产品的列表,那么正如其他人指出的那样,您需要的是一个连接。

当你有几个列表,但你不知道具体有多少,用这个:

listsOfProducts包含很少的对象列表。

List<Product> productListMerged = new List<Product>();

listsOfProducts.ForEach(q => q.ForEach(e => productListMerged.Add(e)));
// I would make it a little bit more simple

 var products = new List<List<product>> {item1, item2, item3 }.SelectMany(id => id).ToList();

这样它是一个多维的列表,. selectmany()将它平铺成一个产品的IEnumerable,然后我使用. tolist()方法。