How do you know if there are duplicates in one list compared to another?

I have a list where MyClass has a 'Name' property. I want to know if there is a duplicate MyClass with the same name in the list.

Also, I have another list and I want to know if there are duplicates compared to List A.

+2


source to share


2 answers


To answer the first question

I want to know if there is a duplicate of MyClass with the same name in the list.

You can do it:

bool hasDuplicates = 
  listA.Count != listA.Select(c => c.Name).Distinct().Count();

      



In response to the second question

Also, I have another List and I want to know if there are any duplicates compared to List A.

You can do it:

bool hasDuplicates = 
  differentList.Select(c => c.Name).Intersect(listA.Select(c => c.Name)).Any();

      

+6


source


To check for duplicate names within one List<MyClass>

list

:

var names = new HashSet<String>();
foreach (MyClass t in list)
    if(!names.Add(t.Name))
        return "Duplicate name!"
return "No duplicates!"

      



or options depending on what you want to do when there are / are not duplicated. In the case of two separate lists, just create a set names

from one list and loop with this type of check on the other (the details depend on what should have happened for duplicate names only in the first list, in the second list only, or only between one list and another, when each of them without duplicates, when considered separately - your specifications are too imprecise to let me guess what you want or expect in each of the many possible combinations!

+2


source







All Articles