开发者

Concatenating two lists of different types with LINQ

开发者 https://www.devze.com 2023-03-30 22:22 出处:网络
Is it possible to concat two list that are of differ开发者_StackOverflowent types? string[] left = { \"A\", \"B\", \"C\" };

Is it possible to concat two list that are of differ开发者_StackOverflowent 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


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>();


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!


Only way I know to make this work would be:

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

精彩评论

暂无评论...
验证码 换一张
取 消