Merge 2 list c# code example
Example 1: 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 2: 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);
}