Is there a Linq operation to determine if there are items in a collection that have the same value for a pair of properties?
C #: I have a collection of objects. T has 2 properties. Property A and Property B. The rule that this collection must adhere to is that the combination of values ββfor A and B must be unique in the collection. In other words, A and B should be used as a composite primary key.
Is there a Linq operation I can use to test this condition? I expect it to be something like
if (items.Select(x => x.Name).Distinct().Count() != items.Select(x => x.Name).Count())
The above statement is how I can check if there are items in the collection that have duplicate names, but I don't know how to do this for more than one property.
source to share
Use an anonymous type to select a composite key like
int totalCount = items.Count();
int distinctCount = items.Select(x => new { x.Name, x.Other })
.Distinct()
.Count();
Anonymous types automatically implement equality and hash codes based on their properties (and the default comparison for those property types).
source to share
You can enter your own comparison matcher. An example is here: http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/c5b71644-b2d9-422b-b7fe-ef3bef30bbac/
source to share