使用LINQ过滤列表 [英] Filtering lists using LINQ
问题描述
我有一个从外部应用程序返回的人员列表,我正在本地应用程序中创建排除列表,以便为我提供从列表中手动删除人员的选项.
I've got a list of People that are returned from an external app and I'm creating an exclusion list in my local app to give me the option of manually removing people from the list.
我有一个已创建的复合密钥,对于两者而言,这是共同的,我想找到一种使用列表"从列表中删除人员的有效方法
I have a composite key which I have created that is common to both and I want to find an efficient way of removing people from my List using my List
例如
class Person
{
prop string compositeKey { get; set; }
}
class Exclusions
{
prop string compositeKey { get; set; }
}
List<Person> people = GetFromDB;
List<Exclusions> exclusions = GetFromOtherDB;
List<Person> filteredResults = People - exclustions using the composite key as a comparer
我认为LINQ是执行此操作的理想方法,但是在尝试了连接,扩展方法,使用yields等之后,我仍然遇到麻烦.
I thought LINQ was the ideal way of doing this but after trying joins, extension methods, using yields, etc. I'm still having trouble.
如果这是SQL,我将使用not in (?,?,?)
查询.
If this were SQL I would use a not in (?,?,?)
query.
推荐答案
Have a look at the Except method, which you use like this:
var resultingList =
listOfOriginalItems.Except(listOfItemsToLeaveOut, equalityComparer)
您将要使用链接到的重载,它使您可以指定自定义IEqualityComparer.这样,您可以根据组合键指定项目的匹配方式. (不过,如果您已经覆盖了Equals,则不需要IEqualityComparer.)
You'll want to use the overload I've linked to, which lets you specify a custom IEqualityComparer. That way you can specify how items match based on your composite key. (If you've already overridden Equals, though, you shouldn't need the IEqualityComparer.)
编辑:由于您似乎正在使用两种不同类型的类,因此这是另一种可能更简单的方法.假设一个名为persons
的List<Person>
和一个名为exclusions
的List<Exclusion>
:
Since it appears you're using two different types of classes, here's another way that might be simpler. Assuming a List<Person>
called persons
and a List<Exclusion>
called exclusions
:
var exclusionKeys =
exclusions.Select(x => x.compositeKey);
var resultingPersons =
persons.Where(x => !exclusionKeys.Contains(x.compositeKey));
换句话说:从排除项中仅选择键,然后从人员中选择所有没有具有任何键的Person对象.
In other words: Select from exclusions just the keys, then pick from persons all the Person objects that don't have any of those keys.
这篇关于使用LINQ过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!