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

例如,

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

当前回答

你可以使用Concat扩展方法:

var result = productCollection1
    .Concat(productCollection2)
    .Concat(productCollection3)
    .ToList();

其他回答

你可以使用Concat扩展方法:

var result = productCollection1
    .Concat(productCollection2)
    .Concat(productCollection3)
    .ToList();
// 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将通过添加额外的元素来改变(突变)一个现有的列表:

list1.AddRange(list2); // list1 now also has list2's items appended to it.

或者,在现代的不可变风格中,你可以在不改变现有列表的情况下投影出一个新的列表:

Concat,它表示list1的项的无序序列,后面跟着list2的项:

var concatenated = list1.Concat(list2).ToList();

不太一样的是,Union投射了一个截然不同的项目序列:

var distinct = list1.Union(list2).ToList();

注意,为了让Union的“值类型不同”行为在引用类型上工作,你需要为你的类定义相等比较(或者使用记录类型的内置比较器)。

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

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

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