c# - Linq Group By, Skip 1 where the skipped 1 was the most recent -
i have data set of objects have stored in events list (the variables have been declared earlier @ class level):
[setup] public void setup() { eventlogobj = new eventlogobj(); event1 = new eventlogobj() { recordid = 1, tablekey = "person_code=1", status = "s", eventtime = convert.todatetime("2013-07-15 14:00:00") }; event2 = new eventlogobj() { recordid = 2, tablekey = "person_code=2", status = "s", eventtime = convert.todatetime("2013-07-15 13:00:00") }; event3 = new eventlogobj() { recordid = 3, tablekey = "person_code=3", status = "s", eventtime = convert.todatetime("2013-07-15 13:00:00") }; event4 = new eventlogobj() { recordid = 4, tablekey = "person_code=2", status = "s", eventtime = convert.todatetime("2013-07-15 14:00:00") }; event5 = new eventlogobj() { recordid = 5, tablekey = "person_code=1", status = "s", eventtime = convert.todatetime("2013-07-15 13:00:00") }; events = new list<eventlogobj>() { event1, event2, event3, event4, event5 }; }
i extracting duplicates - worked (below)
[test] public void storeonlyduplicatedetailsfromrowsintocollection() { var duplicates = events.groupby(s => s.tablekey) .selectmany(grp => grp.skip(1)).tolist(); assert.areequal(2, duplicates.count); }
however, want extract duplicates lowest dates , i'm not quite sure how adjust linq query setup.
here have done far fails.
if wondering duplicates2 is, failed attempt implement this: linq: group aggregate still information recent row?
[test] public void pickduplicateeventwithleastdate() { var duplicates = events //.orderby(e => e.eventtime) .groupby(s => s.tablekey) .selectmany(grp => grp.skip(1)) .tolist(); var duplicates2 = res in events group res res.tablekey g select new { count = g.count(), memberid = g.key, mostrecent = g.orderbydescending(x => x.eventtime) .first() }; assert.areequal(2, duplicates.count); var e1 = duplicates[0]; var e2 = duplicates[1]; assert.areequal(e1.eventtime, convert.todatetime("2013-07-15 13:00:00")); assert.areequal(e2.eventtime, convert.todatetime("2013-07-15 13:00:00")); }
if want try without having setup interfaces, classes, etc in visual studio, see here https://dotnetfiddle.net/yyosfm , fiddle about. if tests pass, should nothing in 'console window'.
you skipping first item, must 1 highest date. achieve this, need use orderbydescending
belongs inside selectmany
before skip
.
var duplicates = events .groupby(s => s.tablekey) .selectmany(grp => grp.orderbydescending(e => e.eventtime) .skip(1)) .tolist();
if want remaining duplicates ordered ascending, add .orderby(e => e.eventtime)
right after skip
.
oh, , test data bogus. first data item person_code=1
2013-07-13 should on 2013-07-15 pass test suite.
Comments
Post a Comment