Thursday, August 04, 2011

How to add two same type of List<> Objects into third same type of List<> Object in C#.NET


How to add two same type of List<> Objects into third same type of List<> Object in C#.NET  
  
For adding multiple objects into some other object, it’s common requirement, Let’s see below the example for this

List<Country> Con1 = new List<Country>(); 
List<Country> Con2 = new List<Country>(); 
List<Country> Con3 = new List<Country>();

Let say you have Con1 and Con2, your requirement to Add these two objects into Con3

Way -1

Con3 = AddCountryList(Con3, Con1); 
Con3 = AddCountryList(Con3, Con2);

private List<Country> AddCountryList(List<Country> finalObject, List<country> sourceObject)
{
    foreach (Country ctn in sourceObject)
     {
         finalObject.Add(ctn);
     }
  return finalObject;
}

Way -2

You can use List<> object method called “AddRange” to achieve this

Con3.AddRange(Con1);
Con3.AddRange(Con2);

No comments: