C# – Find duplicate in a list of a list of integers

algorithmsclist

What is the best way to find the duplicates in a list of a list of integers (no matter what position thay are in)?
I don't necessary need code just the best way to go about this problem.

eg:

List<List<int>> TestData = new List<List<int>>
{
     new List<int> { 1, 2, 3 },
     new List<int> { 2, 1, 3 },
     new List<int> { 6, 8, 3 },
     new List<int> { 9, 2, 4 },
};

The idea is that this will return

2x) 1,2,3
1x) 6,8,3
1x) 9,2,4

I've been breaking my head over this seemingly very simple question but for some reason I can't figure it out.
Hope someone is able to help, Like I said code not necessary but greatly appreciated.

Best Answer

  • Sort each once
  • First compare length
  • Then compare element by element
    As soon as an element does not match then the List does not match

This site is not about code but this works

IEqualityComparer<List<int>> listComparer = new ListComparer();
testData.ForEach(l => l.Sort());
var distinctLists = testData
    .GroupBy(j => j, listComparer)
    .Select(group => new { List = group.Key, Count = group.Count() });

public class ListComparer : IEqualityComparer<List<int>>
{
    public bool Equals(List<int> x, List<int> y)
    {
        if (x.Count != y.Count)
            return false;
        for (int i = 0; i < x.Count; i++)
            if (x[i] != y[i]) return false;
        return true;
    }
    public int GetHashCode(List<int> x) => x.Count;
}