Select distinct in Entity Framework

c# entity-framework linq-to-entities

Question

I have a table called Tag with a column called Label and a column called AuctionId. I also have an array of strings which are search terms. I want to write some Linq to Entities code which will give me a distinct list of AuctionIds where the the Label matches one of the search terms. Here is the pseudocode for this:

return a list of unique AuctionIds where Label is in searchTerms

How can this be done?

1
7
4/20/2015 9:33:34 AM

Accepted Answer

You can use Contains() on the list.

List<String> AuctionIDs = (from tagItem in Tags
                           where searchItems.Contains(tagItem.Label)
                           select tagItem.AutionID).Distinct().ToList();
15
2/17/2012 11:40:36 AM

Popular Answer

Using Lambda notation for clarity, this breaks down to a number of functions in sequence as follows:

IEnumerable<Int32> DistinctIds = TagTable.Where(x => searchTerms.Contains(x.Label)).Select( x => x.AuctionId).Distinct()

Without going too far into the Lambda syntax, the key features here are:

.Where(x => searchTerms.Contains(x.Label)) - this will select out only rows where the searchTerms collection contains the Label value for that row

.Select( x => x.AuctionId) - return out only the integer AutionId values rather than the full record

.Distinct() - does just what it says on the tine

Hope this helps



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow