//Here I have a List of Lists
List<List<T>> SelectionList = new List<List<T>>();
//My current code to compare lists
for(int i = 0; i < SelectionList.Count; i++)
{
for(int j = 0; j < SelectionList.Count; j++)
{
if (SelectionList[i].Equals(SelectionList[j]))
{
SelectionList.Remove(SelectionList[j]);
}
}
}
//Note: The above code supposedly works, in cases where the contents of both the lists are ordered ie., they are in same index, but in my lists they might be same but list contents are shuffled. in this case it fails to identify.
//Basically I need to remove any repetitions of same list in my list of lists;
If (and only if) the following is true:
Tof your list elements implementsIComparableandGetHashCode()correctlyThen you can remove each list that matches an earlier list like so (note that you must traverse the list backwards when removing items from the end of it otherwise the loop indices could go out of range):
The important line here is:
!lists[i].Except(lists[j]).Any().Let's break it down:
lists[i].Except(lists[j]): - This produces a sequence of all the elements oflists[i]that are NOT inlists[j], regardless of order.Thus if all of the items in
lists[j]are also inlists[j], this will produce an empty sequence; otherwise, it will produce a non-empty sequence.The
.Any()will returntruefor a non-empty sequence, andfalsefor an empty sequence.So
lists[i].Except(lists[j]).Any()will returnfalseif the items are the same in each list andtrueif they differ.This is the opposite of what we want for the
lists.RemoveAt()so we just negate the result, giving the final code!lists[i].Except(lists[j]).Any().Compilable console app:
Try it on DotNetFiddle: https://dotnetfiddle.net/nWnOcP