2


I have a problem with getting only the distinct lists.
So I have :

List<List<int>> combinations = new List<List<int>>();
combinations.Add(new List<int> {1,1});
combinations.Add(new List<int> {1,2});
combinations.Add(new List<int> {1,1}); // Same
combinations.Add(new List<int> {1,3});

What I need to do is to get only :

{1,1}
{1,2}
{1,3}

I tried with this : combinations = combinations.Distinct().ToList(); But it does not work.
Any ideas. Thank you in advance.

Ivailo Korakov
  • 357
  • 2
  • 14

3 Answers3

13

You can use your own comparer:

var distincts = 
    combinations
    .Distinct(new ListOfIntComparer());    

class ListOfIntComparer : IEqualityComparer<List<int>>
{
    public bool Equals(List<int> a, List<int> b)
    {
        return
            a.SequenceEqual(b);
    }

    public int GetHashCode(List<int> l)
    {
        unchecked
        {
            int hash = 19;
            foreach (var foo in l)
            {
                hash = hash * 31 + foo.GetHashCode();
            }
            return hash;
         }
    }
}

GetHasCode() implementation from Jon Skeet here.

Community
  • 1
  • 1
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
  • It's worth noting that `GetHashCode()` only has to ensure that if two objects are equal then they have the same hash code and not the other way round. So an implementation as simple as `return l.Count;` could be sufficient, and might be more performant if you have long lists of varying lengths. – Matthew Strawbridge Feb 05 '16 at 14:41
1

Trying to come up with the shortest oneliner. This is what i come up with. Hope it helps you.

var unique = combinations.GroupBy(x => string.Join(",", x), (g, items) => items.First());
fhogberg
  • 415
  • 3
  • 11
-6

Try adding a regular int array:

List<List<int>> lli = new List<List<int>>();

lli.Add((new int[] { 2, 4 }).ToList<int>());
Anthony Dekimpe
  • 357
  • 2
  • 14