串联不同类型的LINQ的两个列表 [英] Concatenating two lists of different types with LINQ

查看:97
本文介绍了串联不同类型的LINQ的两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能Concat的两个列表是不同类型的?

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



上面的代码obciously有一个类型的错误。它的工作原理如果类型匹配(例如:都是整数或字符串)。

The code above obciously has a type error. It works if the types match (eg. both are ints or strings).

POM

推荐答案

您可以框它

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



结果的IEnumerable<对象>

然后拆箱它,你可以使用 OfType< T>()

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

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

这篇关于串联不同类型的LINQ的两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆