查找所有相交数据,而不仅仅是唯一值 [英] Find all intersecting data, not just the unique values

查看:44
本文介绍了查找所有相交数据,而不仅仅是唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我理解了Intersect,但事实证明我错了.

I thought that I understood Intersect, but it turns out I was wrong.

 List<int> list1 = new List<int>() { 1, 2, 3, 2, 3};
 List<int> list2 = new List<int>() { 2, 3, 4, 3, 4};

 list1.Intersect(list2) =>      2,3

 //But what I want is:
 // =>  2,3,2,3,2,3,3

我可以想像这样的方式:

I can figure a way like:

 var intersected = list1.Intersect(list2);
 var list3 = new List<int>();
 list3.AddRange(list1.Where(I => intersected.Contains(I)));
 list3.AddRange(list2.Where(I => intersected.Contains(I)));

LINQ中是否有更简单的方法来实现这一目标?

Is there a easier way in LINQ to achieve this?

我确实需要声明,我不在乎结果以什么顺序给出.

I do need to state that I do not care in which order the results are given.

2,2,2,3,3,3,3也完全可以.

2,2,2,3,3,3,3 would also be perfectly OK.

问题是我正在一个非常大的收藏中使用它,所以我需要效率.

Problem is that I am using this on a very large collection, So I need efficiency.

我们在谈论对象,而不是整数.整数仅是简单的例子,但我意识到这可以有所作为.

We are talking about Objects, not ints. The ints were just for the easy example, but I realize this can make a difference.

推荐答案

让我们看看我们是否可以准确地表征您想要的东西.如果我错了,请纠正我.您需要:列表1的所有元素依次出现在列表2中,然后依次列出列表2的所有元素也出现在列表1中.是吗?

Let's see if we can precisely characterize what you want. Correct me if I am wrong. You want: all elements of list 1, in order, that also appear in list 2, followed by all elements of list 2, in order, that also appear in list 1. Yes?

看起来很简单.

return list1.Where(x=>list2.Contains(x))
     .Concat(list2.Where(y=>list1.Contains(y)))
     .ToList();

请注意,这对于大型列表来说效率不高.如果每个列表都有一千个项目,那么这将进行两百万次比较.如果您遇到这种情况,则想使用更有效的数据结构来测试成员资格:

Note that this is not efficient for large lists. If the lists have a thousand items each then this does a couple million comparisons. If you're in that situation then you want to use a more efficient data structure for testing membership:

list1set = new HashSet(list1);
list2set = new HashSet(list2);

return list1.Where(x=>list2set.Contains(x))
     .Concat(list2.Where(y=>list1set.Contains(y)))
     .ToList();

仅进行数千次比较,但可能会占用更多内存.

which only does a couple thousand comparisons, but potentially uses more memory.

这篇关于查找所有相交数据,而不仅仅是唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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