Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query to detect duplicate properties in a list of objects

I have a list of objects. These objects are made up of a custom class that basically contains two string fields String1 and String2.

What I need to know is if any of these strings are duplicated in that list. So I want to know if objectA.String1 == objectB.String1, or ObjectA.String2 == ObjectB.String2, or ObjectA.String1 == ObjectB.String", or ObjectA.String2 == ObjectB.String1.

Also, I want to mark each object that contains a duplicate string as having a duplicate string (with a bool HasDuplicate on the object).

So when the duplication detection has run I want to simply foreach over the list like so:

foreach (var item in duplicationList)
    if (item.HasDuplicate)
        Console.WriteLine("Duplicate detected!");

This seemd like a nice problem to solve with LINQ, but I cannot for the life of me figure out a good query. So I've solved it using 'good-old' foreach, but I'm still interested in a LINQ version.

like image 331
Jeroen-bart Engelen Avatar asked Dec 08 '22 05:12

Jeroen-bart Engelen


1 Answers

Here's a complete code sample which should work for your case.

class A
{
    public string Foo   { get; set; }
    public string Bar   { get; set; }
    public bool HasDupe { get; set; }
}

var list = new List<A> 
          { 
              new A{ Foo="abc", Bar="xyz"}, 
              new A{ Foo="def", Bar="ghi"}, 
              new A{ Foo="123", Bar="abc"}  
          };

var dupes = list.Where(a => list
          .Except(new List<A>{a})
          .Any(x => x.Foo == a.Foo || x.Bar == a.Bar || x.Foo == a.Bar || x.Bar == a.Foo))
          .ToList();

dupes.ForEach(a => a.HasDupe = true);
like image 121
Winston Smith Avatar answered Dec 10 '22 01:12

Winston Smith