c# merge two lists different types

List<string> a = new List<string>();
List<string> b = new List<string>();

a.AddRange(b);

4.13
9
Krish 100200 points

                                    // Create your object
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;} }

// Construct your lists
List&lt;A&gt; list = new List&lt;A&gt;() { new A( Id = 1 ), new A( Id = 2 ) };
List&lt;B&gt; list1 = new List&lt;B&gt;() { new B( Id = 3 ), new B( Id = 4 ) };

// Then create a linq query and convert the result to a list
List&lt;object&gt; all = (from x in list select (object)x).ToList();

// Now add the second list to the end of the last one
all.AddRange((from x in list1 select (object)x).ToList());

// You can use this new list to loop it like this
foreach (object item in all)
{
	// If you want to check which object we are looping you do this:
	bool obj1 = item is A;
	// Now you can cast the item to your object in a conditional operator
	Console.WriteLine(obj1 ? (item as A).Id : (item as B).Id);

	// Output:
	// 1
	// 2
  	// 3
  	// 4
}

4.13 (8 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source