c# merge two lists code example
Example 1: combine two lists c#
List<string> a = new List<string>();
List<string> b = new List<string>();
a.AddRange(b);
Example 2: c# merge two lists
public class A { int Id { get; set; } A() { } A(int id) { Id = id;} }
public class B { int Id { get; set; } B() { } B(int id) { Id = id;} }
List<A> list = new List<A>() { new A( Id = 1 ), new A( Id = 2 ) };
List<B> list1 = new List<B>() { new B( Id = 3 ), new B( Id = 4 ) };
List<object> all = (from x in list select (object)x).ToList();
all.AddRange((from x in list1 select (object)x).ToList());
foreach (object item in all)
{
bool obj1 = item is A;
Console.WriteLine(obj1 ? (item as A).Id : (item as B).Id);
}
Example 3: c# merge two lists different types
public class A { int Id { get; set; } A() { } A(int id) { Id = id;} }
public class B { int Id { get; set; } B() { } B(int id) { Id = id;} }
List<A> list = new List<A>() { new A( Id = 1 ), new A( Id = 2 ) };
List<B> list1 = new List<B>() { new B( Id = 3 ), new B( Id = 4 ) };
List<object> all = (from x in list select (object)x).ToList();
all.AddRange((from x in list1 select (object)x).ToList());
foreach (object item in all)
{
bool obj1 = item is A;
Console.WriteLine(obj1 ? (item as A).Id : (item as B).Id);
}
Example 4: c# merge two lists as queryable
var list3 = list1.Concat(list2);
var list4 = list1.Union(list2);