How do you know if there are duplicates in one list compared to another?
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();
source to share
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!
source to share