Saeid
Saeid

Reputation: 13582

Exclude a collection from another by lambda

This is my type:

public class myType
 {
     public int Id { get; set; }
     public string name { get; set; }
 }

And there is 2 collection of this type:

List<myType> FristList= //fill ;
List<myType> Excludelist= //fill;

And I need to exclude Excludelist from FristList something like the following:

List<myType> targetList = 
FirstList.Where(m=>m.Id  not in (Excludelist.Select(t=>t.Id));

What is your suggestion about the exact lambda expression of the above query?

Upvotes: 3

Views: 10245

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500675

Three options. One without any changes:

var excludeIds = new HashSet<int>(excludeList.Select(x => x.Id));
var targetList = firstList.Where(x => !excludeIds.Contains(x.Id)).ToList();

Alternatively, either override Equals and GetHashCode and use:

var targetList = firstList.Except(excludeList).ToList();

Or write an IEqualityComparer<MyType> which compares by IDs, and use:

var targetList = firstList.Except(excludeList, comparer).ToList();

The second and third options are definitely nicer IMO, particularly if you need to do this sort of work in various places.

Upvotes: 17

Related Questions