Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating two lists of different types with LINQ

Tags:

c#

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

like image 330
Pompair Avatar asked Aug 25 '11 12:08

Pompair


1 Answers

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>();
like image 135
Daniel A. White Avatar answered Nov 02 '22 04:11

Daniel A. White