c# - Get latest record and group with highest date - LINQ -
i have table billing
below
accoundid | group | dateofbill 1234 | | 2017-07-12 1234 | b | 2017-07-16 1234 | c | 2017-07-31 1235 | | 2017-07-31 1236 | b | 2017-07-31
as see, accountid
1234 have made 3 transaction on july 2017. need list accountid
1234 must in group
c because that's latest date on transaction.
here code snippet
var latestaccount = n in billing (n.group == "a" || n.group == "b" || n.group == "c") group n new { n.accountid, n.group } g select new { accountid = g.key.accountid, group = g.key.group , dateofbill = g.max(t => t.dateofbill) };
but result wrong. how in linq?
class program { static void main(string[] args) { list<billing> billings = new list<billing>() { new billing() { accountid = 1234, dateofbill = new datetime(2017,07,12), group = "a" }, new billing() { accountid = 1234, dateofbill = new datetime(2017,07,16), group = "b" }, new billing() { accountid = 1234, dateofbill = new datetime(2017,07,31), group = "c" }, new billing() { accountid = 1235, dateofbill = new datetime(2017,07,31), group = "a" }, new billing() { accountid = 1236, dateofbill = new datetime(2017,07,31), group = "b" } }; var latestaccount = n in billings (n.group == "a" || n.group == "b" || n.group == "c") group n new { n.accountid } g select g.where(d => d.dateofbill == g.max(m => m.dateofbill)).select(x => new { accountid = g.key.accountid, group = x.group, dateofbill = x.dateofbill }).firstordefault(); foreach (var item in latestaccount) { console.writeline("accountid: " + item.accountid + " date of bill: " + item.dateofbill + " group: "+ item.group); } console.readline(); } } class billing { public int accountid { get; set; } public string group { get; set; } public datetime dateofbill { get; set; } }
is below want? if show me output want, can modify answer.
Comments
Post a Comment