Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two (or more) lists into one, in C# .NET

Tags:

c#

.net

list

People also ask

How do I consolidate two lists?

We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2. Whereas, list_1 and list_2 remained same as original.

How do I merge lists?

merge() is used to merge two lists into a one. We can simply just merge the two lists, or if we want extra comparisons we can also add a comparator. Before merging two lists we must ensure the lists are in sorted order. If there is no comparator is passed then it merges two lists into one sorted list.


You can use the LINQ Concat and ToList methods:

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

Note that there are more efficient ways to do this - the above will basically loop through all the entries, creating a dynamically sized buffer. As you can predict the size to start with, you don't need this dynamic sizing... so you could use:

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

(AddRange is special-cased for ICollection<T> for efficiency.)

I wouldn't take this approach unless you really have to though.


Assuming you want a list containing all of the products for the specified category-Ids, you can treat your query as a projection followed by a flattening operation. There's a LINQ operator that does that: SelectMany.

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

In C# 4, you can shorten the SelectMany to: .SelectMany(GetAllProducts)

If you already have lists representing the products for each Id, then what you need is a concatenation, as others point out.


you can combine them using LINQ:

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

the more traditional approach of using List.AddRange() might be more efficient though.


Have a look at List.AddRange to merge Lists


You could use the Concat extension method:

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

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