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

例如,

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

当前回答

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

listsOfProducts包含很少的对象列表。

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

listsOfProducts.ForEach(q => q.ForEach(e => productListMerged.Add(e)));

其他回答

你可以使用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>以提高效率。)

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

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

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

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

我知道这是一个老问题,我想我可能只是说说我的意见。

如果你有一个List<Something>[],你可以使用聚合来连接它们

public List<TType> Concat<TType>(params List<TType>[] lists)
{
    var result = lists.Aggregate(new List<TType>(), (x, y) => x.Concat(y).ToList());

    return result;
}

希望这能有所帮助。

你可以使用Concat扩展方法:

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

您需要使用Concat操作