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

例如,

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

当前回答

你可以使用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;
}

希望这能有所帮助。

列表。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的“值类型不同”行为在引用类型上工作,你需要为你的类定义相等比较(或者使用记录类型的内置比较器)。

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

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

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

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

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

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