Casey Crookston
Casey Crookston

Reputation: 13955

Isolate duplicate objects in a list of objects

Given a list of objects with possible duplicates, I can find plenty of examples of how to get a List<IGrouping<'a, MyObject>> or how to remove duplicates. But what I want to do is just isolate the duplicates in a list of their own, based on a group, and while ignoring the original.

So let's say I have this list:

Prop1     Prop2     Prop3
---------------------------
foo1      bar1      doesntMatter1
foo2      bar2      doesntMatter2
foo2      bar2      doesntMatter21 // first duplicate
foo2      bar2      doesntMatter22 // second duplicate 
foo3      bar2      doesntMatter32

The rule is, the combo of Prop1 and Prop2 can't be duplicated. But Prod3 doesn't matter. So what I would like is a list that looks like this:


Prop1     Prop2     Prop3
---------------------------
foo2      bar2      doesntMatter21
foo2      bar2      doesntMatter22

Here's what I have so far:

class MyObject
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

And...

List<MyObject> myObjects = new();
myObjects.Add(new() { Prop1 = "foo1", Prop2 = "bar1", Prop3 = "doesntMatter1" });
myObjects.Add(new() { Prop1 = "foo2", Prop2 = "bar2", Prop3 = "doesntMatter2" });
myObjects.Add(new() { Prop1 = "foo2", Prop2 = "bar2", Prop3 = "doesntMatter21" });
myObjects.Add(new() { Prop1 = "foo2", Prop2 = "bar2", Prop3 = "doesntMatter22" });
myObjects.Add(new() { Prop1 = "foo3", Prop2 = "bar3", Prop3 = "doesntMatter3" });

var dupes = (myObjects.GroupBy(m => new { m.Prop1, m.Prop2 }).Where(grp => grp.Count() > 1)).ToList();

foreach (var item in dupes)
{
    // How do I get my isolated list of duplicates?
}

dupes ends up being that List<IGrouping<'a, MyObject>>. But I can't figure out how to go from that to my isolated list of duplicates.

Upvotes: 2

Views: 257

Answers (1)

Casey Crookston
Casey Crookston

Reputation: 13955

Ok found it:

var isolatedList = dupes.SelectMany(group => group.Skip(1)).ToList();

Edited per Lance's comment below.

Upvotes: 1

Related Questions