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

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

问题描述

我认为我明白相交,但事实证明我错了。

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.

===更新2 ===
是的,我们所谈论的对象,而不是整数。该整数只是用于简单的例子,但我意识到这可以有所作为。

=== UPDATE 2 === Yes, we are talking about Objects, not ints. The ints were just for the easy example, but I realize this can make a difference.

不过,我发现了一个更好的办法来避免巨大的收藏品的问题,所以给出的答案是我的情况和理解不够好。

However, I found a better way to avoid the problem of having huge collections, so the given answer is good enough for my situation and understanding.

推荐答案

让我们看看我们是否能精确地描述你想要什么。纠正我,如果我错了。你想:清单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.

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

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