简体   繁体   English

查找列表1中不存在且代码最少的行中的所有整数?

[英]Finding all integers that exist in list1 that don't exist in list2 with fewest lines of code?

Let's say I have two lists of integers: 假设我有两个整数列表:

List<int> list1 = new List<int> {1,2,3,4,5,6};
List<int> list2 = new List<int> {4,5,6,7,8,9};

What is the quickest way to find all of the integers that exist in list1 but not list2 查找list1中但list2中不存在的所有整数的最快方法是什么

The simplest solution I can think of is to create a union list from list1 and list2 and remove all of the members from this union that exist in list2 我能想到的最简单的解决方案是从list1和list2创建一个联合列表,并从此联合中删除list2中存在的所有成员

Union = {1,2,3,4,5,6,7,8,9}
Union - list2 = {1,2,3} <- This is my desired result

But maybe there is a simpler and faster one line of code way to get this job done? 但是也许有一种更简单,更快的代码行可以完成这项工作?

list1.Except(list2) (如果使用.NET 3.5)

If the lists can potentially contain duplicate elements and you want to return any duplicates from list1 then you can do something like this: 如果列表可能包含重复的元素,并且您想从list1返回任何重复的元素,则可以执行以下操作:

var tempSet = new HashSet<int>(list2);
var results = list1.Where(x => !tempSet.Contains(x));

If list2 only contains a few elements then you can probably get away without using a HashSet<T> : 如果list2仅包含一些元素,那么您可能无需使用HashSet<T>就可以逃脱:

var results = list1.Where(x => !list2.Contains(x));

Though for larger collections you'll find that the HashSet<T> will easily outperform using the list directly: Contains is O(1) for HashSet<T> and O(n) for arbitrary IEnumerable<T> sequences. 尽管对于较大的集合,您会发现直接使用该列表可以轻松地胜过HashSet<T> :对于HashSet<T>Contains为O(1),对于任意IEnumerable<T>序列, Contains O(n)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM