简体   繁体   中英

Selecting list of object type after grouping in linq

I have a table such as the following:

ProductId, CategoryId
123, Category1
123, Category2
123, Category1

My parameter is productId and I need to return a list of type Category based on distinct categories for the given productId in the above table.

You could leverage the .Distinct() function from LINQ to select all the distinct categories belonging to the specified productId.

var pList = (from p in context.Products 
where p.ProductId == productId 
select p.Category).Distinct().ToList();
var list = context.Products
  .Where(p=>p.ProductId==productId)
  .Distinct();

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