c 23 merge two lists different types

Solutions on MaxInterview for c 23 merge two lists different types by the best coders in the world

showing results for - "c 23 merge two lists different types"
Djibril
24 Apr 2020
1List<string> a = new List<string>();
2List<string> b = new List<string>();
3
4a.AddRange(b);
Jonathan
31 Nov 2019
1// Create your object
2public class A { int Id { get; set; } A() { } A(int id) { Id = id;} }
3public class B { int Id { get; set; } B() { } B(int id) { Id = id;} }
4
5// Construct your lists
6List<A> list = new List<A>() { new A( Id = 1 ), new A( Id = 2 ) };
7List<B> list1 = new List<B>() { new B( Id = 3 ), new B( Id = 4 ) };
8
9// Then create a linq query and convert the result to a list
10List<object> all = (from x in list select (object)x).ToList();
11
12// Now add the second list to the end of the last one
13all.AddRange((from x in list1 select (object)x).ToList());
14
15// You can use this new list to loop it like this
16foreach (object item in all)
17{
18	// If you want to check which object we are looping you do this:
19	bool obj1 = item is A;
20	// Now you can cast the item to your object in a conditional operator
21	Console.WriteLine(obj1 ? (item as A).Id : (item as B).Id);
22
23	// Output:
24	// 1
25	// 2
26  	// 3
27  	// 4
28}
29
similar questions
queries leading to this page
c 23 merge two lists different types