Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list of list,how do I check and delete a whole duplicate list?

What I have tried:

var similarLists = theMainList.GroupBy(i => new {item.ItemID }).Select(ss => ss.FirstOrDefault()).ToList();


But it didn't work
Posted
Updated 30-Dec-17 3:57am
v2

1 solution

To remove duplicate elements in a list, you can use Distinct. However, for Distinct to work on a list of lists, you'll have to create your own IEqualityComparer for two lists and pass that as argument to Distinct:
C#
class ListEqualityComparer<T> : IEqualityComparer<List<T>>
{
    public bool Equals(List<T> list1, List<T> list2)
    {
        if (list1 == list2) return true; // quick check for reference equality
        if (list1 == null || list2 == null) return false; // One list is null and the other is not null. Return false already so we aren't passing 'null' to SequenceEqual below.
        return Enumerable.SequenceEqual(list1, list2);
    }

    public int GetHashCode(List<T> list)
    {
        // See here for information about a 'hash code': https://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=vs.110).aspx

        // I have taken the code below from Jon Skeet's Stack Overflow answer https://stackoverflow.com/a/8094931

        unchecked
        {
            int hash = 19;
            foreach (var foo in list)
            {
                hash = hash * 31 + foo.GetHashCode();
            }
            return hash;
        }
    }
}
Then, you can use Distinct like this:
C#
var similarLists = theMainList.Distinct(new ListEqualityComparer<YOUR SUB-LIST TYPE HERE>()).ToList();
 
Share this answer
 
Comments
Mazin78 30-Dec-17 15:15pm    
I am so thankful, it's great and gives me all what I need.
Thomas Daniels 30-Dec-17 15:15pm    
You're welcome!
BillWoodruff 31-Dec-17 0:15am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900