Home > Net >  GroupBy with Where clause LINQ query
GroupBy with Where clause LINQ query

Time:05-21

I have a question, I want to use Group by with Where clause. Here is the scenario, I want get all the orders of a user and group by them with ordernumber so it doesn't show me multiple orders with same order number. I tried to use LINQ query but that doesn't seemed to work. Does anyone have any idea?

var result = Entity.Where(x => x.UserId == Guid.Parse(userId)).GroupBy(x => x.OrderNumber).ToList();

This is what I tried.

CodePudding user response:

I just tried to reproduce the behavior. The query itself seems to work fine. The elements are grouped and contain a field "ResultView" for the individual elements of a group.

How exactly is it not working for you? What is the result, that you get?

CodePudding user response:

You can get first record from group.

var result = Entity
   .Where(x => x.UserId == Guid.Parse(userId))
   .GroupBy(x => x.OrderNumber)
   .Select(g => g.First())
   .ToList();
  • Related