Combining two lists of different types using LINQ

Is it possible to concatenate two lists of different types?

string[] left = { "A", "B", "C" }; int[] right = { 1, 2, 3 }; var result = left.Concat(right); 

There is a type error in the above code. It works if the types are the same (for example, both are int or strings).

POM

+6
source share
3 answers

You can paste it.

 var result = left.Cast<object>().Concat(right.Cast<object>()); 

result will be IEnumerable<object> .

Then, to unzip it, you can use OfType<T>() .

 var myStrings = result.OfType<string>(); var myInts = result.OfType<int>(); 
+14
source

You can use both types of a generic type (in this case, object ), or you can convert the types of one of the lists so you can combine them:

 right.Select(i = i.ToString()) 

or

 left.Select(s => int.Parse(s)) // Careful of exceptions here! 
0
source

The only way I know to do this job:

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

Source: https://habr.com/ru/post/895868/


All Articles