Search code examples
c#linqgeneric-listexcept

How to find not matching records in Generic List in C#


I have two Generic List object, I want to get records which are not matching in second Generic list object. Below is my code. But it returning all records.

I want to ignore matching record in first list.

public class CuratedIncludeUid
    {
        public string type { get; set; }
        public string uid { get; set; }
    }

List<CuratedIncludeUid> newUids = new List<CuratedIncludeUid>();
            newUids.Add(new CuratedIncludeUid { type = "series", uid = "600" });

            List<CuratedIncludeUid> liExistingUids = new List<CuratedIncludeUid>();
            liExistingUids.Add(new CuratedIncludeUid { type = "series", uid = "600" });
            liExistingUids.Add(new CuratedIncludeUid { type = "series", uid = "200" });

            var ied = liExistingUids.Except(newUids).ToList(); ;
            foreach (var row in ied)
            {
                Console.WriteLine("Uid:" + row.uid + "type:" + row.type);
            }
            Console.Read();

I am getting Output as below 
Uid:600type:series
Uid:200type:series

**My expected output as below
Uid:200type:series**

Solution

  • Either, you can implement Equals and GetHashCode or IEqualityComparer, or you can also do the following:

    With All:

    var ied = liExistingUids.Except(newUids).ToList();
    liExistingUids
      .Where(x => newUids.All(y => y.type != x.type && y.series != x.series))
      .ToList();
    

    With Any:

    liExistingUids
      .Where(x => !newUids.Any(y => y.type == x.type && y.series == x.series))
      .ToList();