0

In C#, I have the following Class:

public class SQLColour
{
    public string ID { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string CorporateID { get; set; }
}

I have a List<SQLColour> called List1 and a List<SQLColour> called List2.

How can I return a List<SQLColour> that has items that have an ID that exists in List1 but not in List2?

Thanks in advance

user2985419
  • 553
  • 3
  • 9
  • 23
  • 1
    This might help: http://stackoverflow.com/questions/3944803/use-linq-to-get-items-in-one-list-that-are-not-in-another-list – sgeddes May 13 '14 at 03:04

1 Answers1

1

I usually use the following pattern, as Enumerable.Except does not accept a generic predicate:

// Find all IDs in List2, using a HashSet to improve bounds
var idsList2 = new HashSet(List2.Select(x => x.Id));

// Select from List1 only elements which ID does not appear in List2
var onlyList1ById = List1.Where(x => !idsList2.Contains(x.Id));

The HashSet is not required but it has better bounds and is thus my standard pattern.

user2864740
  • 60,010
  • 15
  • 145
  • 220