相交在C#两个列表 [英] Intersect Two Lists in C#

查看:109
本文介绍了相交在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
}

这篇关于相交在C#两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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