Filtering lists using LINQ

前端 未结 9 2058
暖寄归人
暖寄归人 2021-02-04 00:23

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

9条回答
  •  迷失自我
    2021-02-04 00:32

    Have a look at the Except method, which you use like this:

    var resultingList = 
        listOfOriginalItems.Except(listOfItemsToLeaveOut, equalityComparer)
    

    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.)

    Edit: Since it appears you're using two different types of classes, here's another way that might be simpler. Assuming a List called persons and a List called exclusions:

    var exclusionKeys = 
            exclusions.Select(x => x.compositeKey);
    var resultingPersons = 
            persons.Where(x => !exclusionKeys.Contains(x.compositeKey));
    

    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.

提交回复
热议问题