Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last record of each group in entityframework?

I want to retrieve last inserted record of each MobileNo in entity-framework.

Here is my table data.

ID      RegNo       MobileNo    CreatedDate
26727   190077348   9696562673  13-02-2017 06:31
26729   123782783   9696562673  13-02-2017 06:35
45779   530087328   5878525875  07-02-2017 07:23
99902   120058572   7379130560  08-02-2017 12:39
64477   180073650   7417516480  10-02-2017 13:47
81839   240087264   7754990580  11-02-2017 10:47 

and want output like

ID      RegNo       MobileNo    CreatedDate 
26729   123782783   9696562673  13-02-2017 06:35
45779   530087328   5878525875  07-02-2017 07:23 
99902   120058572   7379130560  08-02-2017 12:39
64477   180073650   7417516480  10-02-2017 13:47
81839   240087264   7754990580  11-02-2017 10:47 
like image 521
Sudhir Panda Avatar asked Feb 16 '17 13:02

Sudhir Panda


1 Answers

Assuming the name of your table is Items:

var result = dbContext.Items.GroupBy(x => x.MobileNo)
                      .Select(x => x.OrderByDescending(y => y.CreatedDate).First());

Running sample: https://dotnetfiddle.net/3ud2pB

like image 166
fubo Avatar answered Nov 12 '22 21:11

fubo