1

as the title says how can i do this ? Let's say i have the following List<List<int>> :

var List = new List<List<int>>();
var temp1 = new List<int>();
var temp2 = new List<int>();
var temp3 = new List<int>();

temp1.Add(0);
temp1.Add(1);
temp1.Add(2);

temp2.Add(3);
temp2.Add(4);
temp2.Add(5);

temp3.Add(0);
temp3.Add(1);
temp3.Add(2);

List.Add(temp1);
List.Add(temp2);
List.Add(temp3);

now list temp1 and temp3are duplicates. How can i remove just one of them ? Not both List.Distinct(); wont work for me.

EDIT Also if multiple list's has length of 0 they should also be removed

KOPEUE
  • 260
  • 4
  • 15
  • 1
    Please refer to [this post](http://stackoverflow.com/questions/12784788/c-sharp-remove-duplicates-from-listlistint) – Emmanuel Ponnudurai Mar 16 '16 at 20:06
  • I modified your title, this is to highlight the difference between your question and the [similar suggestion](http://stackoverflow.com/questions/36045773/remove-duplicates-from-a-listlistint?noredirect=1#comment59740287_36045773) linked by @EmmanuelDurai. – slugster Mar 16 '16 at 20:18
  • Thanks for that i should've originally post it this way – KOPEUE Mar 16 '16 at 20:26

2 Answers2

3

You can do it with Distinct() but using the overload with the comparer:

class ListComparer<T> : EqualityComparer<List<T>>
{
    public override bool Equals(List<T> l1, List<T> l2)
    {
        if (l1 == null && l2 == null) return true;
        if (l1 == null || l2 == null) return false;

        return Enumerable.SequenceEqual(l1, l2);
    }


    public override int GetHashCode(List<T> list)
    {
        return list.Count;
    }
}

And use it like this:

var List = new List<List<int>>();
var temp1 = new List<int>();
var temp2 = new List<int>();
var temp3 = new List<int>();

temp1.Add(0);
temp1.Add(1);
temp1.Add(2);

temp2.Add(3);
temp2.Add(4);
temp2.Add(5);

temp3.Add(0);
temp3.Add(1);
temp3.Add(2);

List.Add(temp1);
List.Add(temp2);
List.Add(temp3);


var comparer = new ListComparer<int>();            
var distinct = List.Distinct(comparer).ToList();

You can firstly remove empty lists:

List = List.Where(l => l.Count > 0).ToList();
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
1

You can also use Linq with SequenceEqual before adding to the list:

Console.WriteLine(temp1.SequenceEqual(temp2));//False
Console.WriteLine(temp1.SequenceEqual(temp3));//True

https://msdn.microsoft.com/en-us/library/bb348567(v=vs.110).aspx