c# - Using Linq to find next element in subset of a list -
i have following collection
// collection query var stagetable = new list<stage> { new stage {stageid = 1, lifecycleid = 1, stageseqno = 1}, new stage {stageid = 2, lifecycleid = 1, stageseqno = 2}, new stage {stageid = 3, lifecycleid = 1, stageseqno = 3}, new stage {stageid = 4, lifecycleid = 1, stageseqno = 4}, new stage {stageid = 5, lifecycleid = 2, stageseqno = 1}, new stage {stageid = 6, lifecycleid = 2, stageseqno = 2}, new stage {stageid = 7, lifecycleid = 2, stageseqno = 3}, new stage {stageid = 8, lifecycleid = 2, stageseqno = 4}, }; and i'm trying construct query return next stage given currentstage contained within same subset defined lifecycleid, e.g., given currentstage = 2 expect stage stageid = 3 back, currentstage = 4 expect null since lifecycleid switches value of 2.
this have
var lifecycleid = stagetable .where(x => x.stageid == currentstageid) .select(x => x.lifecycleid); var nextstage = stagetable .where(s => s.lifecycleid == lifecycleid.first()) .skipwhile(s => s.stageid != currentstageid) .skip(1).firstordefault(); it appears work, there way perform in single query?
if install morelinq nuget package use code like:
var currentstageid = 4; var nextstage = stagetable.skipwhile(z => z.stageid < currentstageid) .lead(1, (x, y) => new { existing = x, next = y }) .take(1) .firstordefault(z => z.next?.lifecycleid == z.existing.lifecycleid)?.next; console.writeline(nextstage?.stageid); skipwhile skip data before current row.
lead merge adjacent rows (i.e. put current , next row together).
take 1 ensure single row (representing current , next row together).
and firstordefault ensure null returned if second row not have same lifecycleid first row).
Comments
Post a Comment