I have a List where MyClass has a property 'Name'. I want to know if there are duplicate MyClass with the same Name in the list.
Also, I have a different List and I want to know if there are any duplicates compared to List A.
I have a List where MyClass has a property 'Name'. I want to know if there are duplicate MyClass with the same Name in the list.
Also, I have a different List and I want to know if there are any duplicates compared to List A.
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 variants depending on what you want to do when there are/aren't duplicates. For the case of two separate lists, just build the names
set from one list, and loop with this kind of check on the other (details depend on what's supposed to happen for duplicate names within the first list only, within the second list only, or only between one list and the other when each is duplicates-free when considered in isolation -- your specs are way too imprecise to allow me to guess what you want or expect in each of the many possible combinations!
To respond to the first question
I want to know if there are duplicate MyClass with the same Name in the list.
you can do this:
bool hasDuplicates =
listA.Count != listA.Select(c => c.Name).Distinct().Count();
In response to the second question
Also, I have a different List and I want to know if there are any duplicates compared to List A.
you can do this:
bool hasDuplicates =
differentList.Select(c => c.Name).Intersect(listA.Select(c => c.Name)) != 0;