Reputation: 7311
Is it possible to concat two list that are of different types?
string[] left = { "A", "B", "C" };
int[] right = { 1, 2, 3 };
var result = left.Concat(right);
The code above obciously has a type error. It works if the types match (eg. both are ints or strings).
pom
Upvotes: 7
Views: 2809
Reputation: 2630
Only way I know to make this work would be:
var result = left.Concat(right.Select(i = i.ToString()));
Upvotes: 0
Reputation: 190925
You can box it.
var result = left.Cast<object>().Concat(right.Cast<object>());
result
will be IEnumerable<object>
.
Then to unbox it, you can use OfType<T>()
.
var myStrings = result.OfType<string>();
var myInts = result.OfType<int>();
Upvotes: 15
Reputation: 32428
You could cast both to a common base type (in this case object
), or you could convert the types of one of the lists so you can combine them, either:
right.Select(i = i.ToString())
or
left.Select(s => int.Parse(s)) // Careful of exceptions here!
Upvotes: 0