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

C#.NetList

C# Problem Overview


Is it possible to convert two or more lists into one single list, in .NET using C#?

For example,

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

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

Have a look at List.AddRange to merge Lists

Solution 5 - C#

You could use the Concat extension method:

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

Solution 6 - C#

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

Solution 7 - C#

I know this is an old question I thought I might just add my 2 cents.

If you have a List<Something>[] you can join them using Aggregate

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

    return result;
}

Hope this helps.

Solution 8 - C#

// I would make it a little bit more simple

 var products = new List<List<product>> {item1, item2, item3 }.SelectMany(id => id).ToList();

This way it is a multi dimensional List and the .SelectMany() will flatten it into a IEnumerable of product then I use the .ToList() method after.

Solution 9 - C#

I've already commented it but I still think is a valid option, just test if in your environment is better one solution or the other. In my particular case, using source.ForEach(p => dest.Add(p)) performs better than the classic AddRange but I've not investigated why at the low level.

You can see an example code here: https://gist.github.com/mcliment/4690433

So the option would be:

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

productCollection1.ForEach(p => allProducts.Add(p));
productCollection2.ForEach(p => allProducts.Add(p));
productCollection3.ForEach(p => allProducts.Add(p));

Test it to see if it works for you.

Disclaimer: I'm not advocating for this solution, I find Concat the most clear one. I just stated -in my discussion with Jon- that in my machine this case performs better than AddRange, but he says, with far more knowledge than I, that this does not make sense. There's the gist if you want to compare.

Solution 10 - C#

To merge or Combine to Lists into a One list.

  • There is one thing that must be true: the type of both list will be equal.

  • For Example: if we have list of string so we can add add another list to the existing list which have list of type string otherwise we can't.

Example:

class Program
{
   static void Main(string[] args)
   {
      List<string> CustomerList_One = new List<string> 
      {
         "James",
         "Scott",
         "Mark",
         "John",
         "Sara",
         "Mary",
         "William",
         "Broad",
         "Ben",
         "Rich",
         "Hack",
         "Bob"
      };

      List<string> CustomerList_Two = new List<string> 
      {
         "Perter",
         "Parker",
         "Bond",
         "been",
         "Bilbo",
         "Cooper"
      };
      
      // Adding all contents of CustomerList_Two to CustomerList_One.
      CustomerList_One.AddRange(CustomerList_Two);

      // Creating another Listlist and assigning all Contents of CustomerList_One.
      List<string> AllCustomers = new List<string>();

      foreach (var item in CustomerList_One)
      {
         AllCustomers.Add(item);
      }

      // Removing CustomerList_One & CustomerList_Two.
      CustomerList_One = null;
      
      CustomerList_Two = null;
      // CustomerList_One & CustomerList_Two -- (Garbage Collected)
      GC.Collect();

      Console.WriteLine("Total No. of Customers : " +  AllCustomers.Count());
      Console.WriteLine("-------------------------------------------------");
      foreach (var customer in AllCustomers)
      {
         Console.WriteLine("Customer : " + customer);
      }
      Console.WriteLine("-------------------------------------------------");

   }
}

Solution 11 - C#

In the special case: "All elements of List1 goes to a new List2": (e.g. a string list)

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

In this case, list2 is generated with all elements from list1.

Solution 12 - C#

You need to use Concat operation

Solution 13 - C#

When you got few list but you don't know how many exactly, use this:

listsOfProducts contains few lists filled with objects.

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzekiaView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#AniView Answer on Stackoverflow
Solution 3 - C#Botz3000View Answer on Stackoverflow
Solution 4 - C#StuartLCView Answer on Stackoverflow
Solution 5 - C#Darin DimitrovView Answer on Stackoverflow
Solution 6 - C#decycloneView Answer on Stackoverflow
Solution 7 - C#sQuir3lView Answer on Stackoverflow
Solution 8 - C#Gringo JaimesView Answer on Stackoverflow
Solution 9 - C#Marc ClimentView Answer on Stackoverflow
Solution 10 - C#Rehan ShahView Answer on Stackoverflow
Solution 11 - C#Arthur ZennigView Answer on Stackoverflow
Solution 12 - C#ArtemView Answer on Stackoverflow
Solution 13 - C#john.kernelView Answer on Stackoverflow