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

例如,

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

当前回答

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

其他回答

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

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

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

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

在特殊情况下:“List1的所有元素都去一个新的List2”:(例如,一个字符串列表)

List<string> list2 = new List<string>(list1);

在本例中,list2使用list1中的所有元素生成。

// 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操作

你可以使用LINQ Concat和ToList方法:

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

注意,还有更有效的方法可以做到这一点——上面的方法基本上会遍历所有条目,创建一个动态大小的缓冲区。由于您可以预测开始时的大小,因此不需要这种动态大小…所以你可以用:

var allProducts = new List<Product>(productCollection1.Count +
                                    productCollection2.Count +
                                    productCollection3.Count);
allProducts.AddRange(productCollection1);
allProducts.AddRange(productCollection2);
allProducts.AddRange(productCollection3);

(AddRange用于ICollection<T>以提高效率。)

我不会采用这种方法,除非你真的必须这么做。