相交在C#两个列表
问题描述:
我有两个列表:
List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};
我想要做类似
var newData = data1.intersect(data2, lambda expression);
该拉姆达前pression应该返回true,如果 DATA1 [指数]的ToString()==数据2 [指数]
答
如果你想返回整数
您需要首先通过调用的ToString()
每个元素的变换数据1,你的情况。
You need to first transform data1, in your case by calling ToString()
on each element.
List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};
var newData = data1.Select(i => i.ToString()).Intersect(data2);
如果你想返回整数
使用此功能。
List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};
var newData = data1.Intersect(data2.Select(s => int.Parse(s));
请注意,这将引发异常,如果不是所有的字符串是数字。所以,你可以做到以下几点首先要检查:
Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:
int temp;
if(data2.All(s => int.TryParse(s, out temp)))
{
// All data2 strings are int's
}