Pompair
Pompair

Reputation: 7311

Concatenating two lists of different types with LINQ

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

Answers (3)

Billy
Billy

Reputation: 2630

Only way I know to make this work would be:

var result = left.Concat(right.Select(i = i.ToString()));

Upvotes: 0

Daniel A. White
Daniel A. White

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

George Duckett
George Duckett

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

Related Questions