30

Given a class with the following definition:

public class MyTestClass
{
    public int ValueA { get; set; }
    public int ValueB { get; set; }
}

How can duplicate values be found in a MyTestClass[] array?

For example,

MyTestClass[] items = new MyTestClass[3];
items[0] = new MyTestClass { ValueA = 1, ValueB = 1 };
items[1] = new MyTestClass { ValueA = 0, ValueB = 1 };
items[2] = new MyTestClass { ValueA = 1, ValueB = 1 };

Contains a duplicate as there are two MyTestClass objects where ValueA and ValueB both = 1

abatishchev
  • 98,240
  • 88
  • 296
  • 433
CatBusStop
  • 3,347
  • 7
  • 42
  • 54

3 Answers3

60

You can find your duplicates by grouping your elements by ValueA and ValueB. Do a count on them afterwards and you will find which ones are duplicates.

This is how you would isolate the dupes :

var duplicates = items.GroupBy(i => new {i.ValueA, i.ValueB})
  .Where(g => g.Count() > 1)
  .Select(g => g.Key);
Hugo Migneron
  • 4,867
  • 1
  • 32
  • 52
5

You could just use Jon Skeet's DistinctBy and Except together to find duplicates. See this Response for his explanation of DistinctBy.

MyTestClass[] items = new MyTestClass[3];
items[0] = new MyTestClass { ValueA = 1, ValueB = 1 };
items[1] = new MyTestClass { ValueA = 0, ValueB = 1 };
items[2] = new MyTestClass { ValueA = 1, ValueB = 1 };

MyTestClass [] distinctItems = items.DistinctBy(p => new {p.ValueA, p.ValueB}).ToArray();
MyTestClass [] duplicates = items.Except(distinctItems).ToArray();

It will only return one item and not both duplicates however.

Community
  • 1
  • 1
DaveH
  • 534
  • 1
  • 7
  • 17
1

MyTestClass should implement the Equals method.

public bool Equals(MyTestClass x, MyTestClass y)
{
    if (Object.ReferenceEquals(x, y)) return true;

    if (Object.ReferenceEquals(x, null) ||
        Object.ReferenceEquals(y, null))
            return false;

        return x.ValueA == y.ValueA && y.ValueB == y.ValueB;
}

Here you have a good article about it.

After that you can get a "clean" list of MyTestClass with "Distinct" method.

zapico
  • 2,396
  • 1
  • 21
  • 45
  • 2
    If Distinct is gonna work, you'll have to do more than implement the Equals method. You should implement the IEquatable interface and make sure that you implement GetHashCode and object equals properly. – Hugo Migneron Apr 08 '11 at 14:42
  • Right, my fault ;-) Anyway it's not too much work... and it can be interesting in many scenarios ;-) – zapico Apr 08 '11 at 14:46