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.

+2


source to share


3 answers


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).

+12


source


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/



0


source


Just select a new anonymous object

var keys = items.Select( x => new { x.Name, x.Other } ).ToList();

if (keys.Distinct().Count() != keys.Count())
{
 ...
}

      

0


source







All Articles