简体   繁体   中英

Entity Framework - Select distinct in

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?

You can use Contains() on the list.

List<String> AuctionIDs = (from tagItem in Tags
                           where searchItems.Contains(tagItem.Label)
                           select tagItem.AutionID).Distinct().ToList();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM