Using LINQ to find duplicates across multiple properties

前端 未结 3 1090
滥情空心
滥情空心 2020-12-31 00:22

Given a class with the following definition:

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


        
相关标签:
3条回答
  • 2020-12-31 01:07

    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.

    0 讨论(0)
  • 2020-12-31 01:13

    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.

    0 讨论(0)
  • 2020-12-31 01:21

    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);
    
    0 讨论(0)
提交回复
热议问题