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);
The lambda expression should return true if data1[index].ToString() == data2[index]
I have two lists:
List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};
I want do to something like
var newData = data1.intersect(data2, lambda expression);
The lambda expression should return true if data1[index].ToString() == data2[index]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要首先转换 data1,在您的情况下,通过在每个元素上调用
ToString()
。如果您想返回字符串,请使用此选项。
如果您想返回整数,请使用此选项。
请注意,如果并非所有字符串都是数字,这将引发异常。因此,您可以先执行以下操作来检查:
You need to first transform data1, in your case by calling
ToString()
on each element.Use this if you want to return strings.
Use this if you want to return integers.
Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:
如果您有对象,而不是结构(或字符串),那么您必须首先将它们的键相交,然后通过这些键选择对象:
If you have objects, not structs (or strings), then you'll have to intersect their keys first, and then select objects by those keys:
从性能角度来看,如果两个列表包含元素数量显着不同,您可以尝试这种方法(使用条件运算符 ?:):
1.首先您需要声明转换器:
2.然后使用条件运算符:
转换较短列表的元素以匹配较长列表的类型。想象一下,如果您的第一个集合包含 1000 个元素,而第二个集合仅包含 10 个元素(或相反,因为这并不重要),那么执行速度;-)
当您希望将结果作为 List 时,在最后一行中您将结果(仅结果)转换回 int。
From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):
1.First you need to declare a converter:
2.Then you use a conditional operator:
You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)
As you want to have a result as List, in a last line you convert the result (only result) back to int.