tags:

views:

138

answers:

1

I need to return a list of counties, but I need to filter out duplicate phone code values. For some reason I'm having trouble with the syntax, can anyone show me how to do this? Should I be using the group by instead?

+1  A: 

Group by would work if you need the actual entity.

var query = db.Counties.GroupBy( c => new { c.CountyName, c.PhoneCode } )
                       .Select( g => g.FirstOrDefault() );

Or if you are constructing it for a view model and only need the data, you could use Distinct. The following creates an anonymous type that could be used to populate the model.

var query = db.Counties.Select( c => new { c.CountyName, c.PhoneCode } )
                       .Distinct();
tvanfosson
Great, the first one did exactly what I was needing, but it's good to know about the second option as well. Thanks for your help!
Victor