Sachin Kainth
Sachin Kainth

Reputation: 46750

Getting unique values using Linq to Entities

I'm using EF and have a context from which I can get a collection of Item objects using _inventoryContext.Items. Now, these item objects have a string value called Carrier. Let's say there are 5 items in Items collection and they have these Carrier values:

"A", "A", "B", "C", "C"

How do I use _inventoryContext.Items to get back the unique carrier values?

"A", "B", "C"

Note that

var carriers = _inventoryContext.Items.Select(i => i.Carrier).Distinct();

does not work; I get "The method 'Distinct' is not supported" with no inner exception.

I'm using SQL Server 2008 Express. Items is a DataServiceQuery<Item> and its Carrier property is a string.

Upvotes: 2

Views: 3655

Answers (1)

Aducci
Aducci

Reputation: 26644

Your example should work, but here is another way you can try

List<string> carriers = _inventoryContext.Items.GroupBy(i => i.Carrier)
                                               .Select(i => i.Key)
                                               .ToList();

Upvotes: 7

Related Questions