views:

125

answers:

2

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.

+1  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!

Alex Martelli
+1 for mentioning HashSet .. thanks :)
Mahesh Velaga
@Mahesh, you're welcome -- hash tables are very general tools (though I can see the point of @gwiz's very .NET specific answer of course, the hash-based approach is very widely portable;-).
Alex Martelli
HashSets are indeed sweet. The asker tagged it C# so I took what IMHO was the C# path of least resistance and greatest readability. I make no claims about its performance =)
gWiz
+1  A: 

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;
gWiz