Select distinct in Entity Framework

c# entity-framework linq-to-entities

Question

I have a table named Tag that has two columns: Label and AuctionId. I also have a string array that contains search keywords. To create a separate list of AuctionIds where the Label matches one of the search phrases, I want to write some Linq to Entities code. The pseudocode for this is as follows:

return a list of unique AuctionIds where Label is in searchTerms

How is this accomplished?

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

Accepted Answer

On the list, you may use Contains().

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

This may be broken down into many functions that are performed in the following order using Lambda notation for clarity:

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

The main characteristics in this case, without getting too far into Lambda syntax, are:

When(x) will only filter out rows where the searchTerms collection includes the label value for that row.

Instead of returning the whole record,.Select(x => x.AuctionId) returns only the integer values for the auction IDs.

Does exactly what it says on the tin:.Distinct()

Hope this is useful.



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