2

I have orders table with IdNumber that is the ID of the user, I need to get the last order of each user (the InsuranceDate is the date).

The problem is how to get the last order if one user can have many orders. how to do it with one query without huge foreach after the entity query ?

public class Order
{
    [Key]
    public int OrderID { get; set; }        
    public string IdNumber { get; set; }
    public int Price { get; set; }
    public Datetime InsuranceDate { get; set; }
}
Daniel Ezra
  • 1,424
  • 3
  • 14
  • 21

2 Answers2

2

Try with this solution:

  var r = db.Orders.GroupBy(o => o.IdNumber).Select(g => g.OrderByDescending(o => o.InsuranceDate).FirstOrDefault());

First, you need to group your orders by the user id. Then, sort in descending order each group and select only the first. This way you will get the last order of each user.

ocuenca
  • 38,548
  • 11
  • 89
  • 102
0

You can try something like this: var result = Orders.OrderByDescending(o => o.InsuranceDate).FirstOrDefault(x => x.IdNumber == userID); where userID is the user's ID that you want to match.

DrewJordan
  • 5,266
  • 1
  • 25
  • 39