[英]Get the difference between two lists using LINQ
I have two lists and I need to compare them and only return a List of Items not in both.我有两个列表,我需要比较它们并且只返回一个不在两个列表中的项目列表。
var listOfIds = new List<int> {1,2,4};
var persons = new ObservableCollection<Person>
{
new Person {Id = 1, Name = "Person 1"},
new Person {Id = 2, Name = "Person 2"},
new Person {Id = 3, Name = "Person 3"},
new Person {Id = 4, Name = "Person 4"}
};
In this example new Person {Id = 3, Name = "Person 3"}
would be the result.在此示例中,结果
new Person {Id = 3, Name = "Person 3"}
。 A Linq solution would be preferred.首选 Linq 解决方案。
not in will work for you不适合你
var listOfIds = new List<int> {1,2,4};
var query = from item in persons
where !listOfIds .Contains( item.id )
select item;
You can check for more detail : SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)您可以查看更多详细信息: SQL to LINQ(案例 7 - 使用 IN 和 NOT IN 子句过滤数据)
您还可以使用 lambda:
var query = persons.Where(item => !listOfIds.Contains(item.Id));
var list1 = new List<int> {1,2,3,4,5};
var list2 = new List<int> {2,3,4,5,6};
list1.Except(list2); //1 - items removed
list2.Except(list1); //6 - items added
With Linq in C# you can do the following variants which give the same results:使用 C# 中的 Linq,您可以执行以下提供相同结果的变体:
int[] numbers1 = { 1,2,3,4 };
int[] numbers2 = { 3,4,5,6 };
// Ac V Bc, thus complement of A plus the complement of B
IEnumerable<int> differencesVariant1 =
numbers1.Except(numbers2).Union(numbers2.Except(numbers1));
// (A V b)c, thus complement of (set A plus set B)
IEnumerable<int> differencesVariant2 =
numbers1.Union(numbers2).Except(numbers1.Intersect(numbers2));
Console.WriteLine("variant 1:");
foreach (int number in differencesVariant1)
Console.WriteLine(number); // prints: 1,2,5,6
Console.WriteLine("variant 2:");
foreach (int number in differencesVariant2)
Console.WriteLine(number); // prints: 1,2,5,6
LINQ now has a function called Except that will implement minus for you. LINQ现在具有一个名为Except的功能,它将为您实现减号。
var a = new List<string>(){"A","B","C", "X", "Y"};
var b = new List<string>(){"B", "C"};
a.Except(b).Dump(); // Dump is a LinqPad function that prints "A", "X", "Y"
10 years later. 10年后。 You can write your own extension method.
您可以编写自己的扩展方法。 With that you don´t need to worry about which set has the longest length.
有了这个,您无需担心哪一组的长度最长。
public static IEnumerable<T> Difference<T>(this IEnumerable<T> set1, IEnumerable<T> set2)
{
IEnumerable<T> biggerSet = set2;
IEnumerable<T> smallerSet = set1;
if(set1.Count() > set2.Count())
{
biggerSet = set1;
smallerSet = set2;
}
return biggerSet.Except(smallerSet);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.