Reputation: 270
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 temp3
are 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
Upvotes: 1
Views: 99
Reputation: 401
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
Upvotes: 1
Reputation: 15982
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();
Upvotes: 3