c# - Neat way of gettings position of my Object in linq collections -
this question has answer here:
- how index using linq? [duplicate] 7 answers
i have object called week. week part of season object. season can contain many weeks. want find position of week (is first week in season (so #1) or second (so #2).
int = 0; foreach ( var w in season.weeks.orderby(w => w.weekstarts)){ if(w.id == id){ return i; } i+=1; }
at moment have. order weeks in second there start date make sure in correct order. , cycle through them until find week matches week looking at. , return int have been counting up..
i feel there should easier linq way feels pretty messy!
if prefer not write findindex
extension method or load sorted items array / list, use overload of select
provides index of item:
return season.weeks .orderby(w => w.weekstarts) .select((week, index) => new { week = week, index = index }) .first(a => a.week.id == id) .index;
if there's no guarantee specified id
exist, use firstordefault
instead:
var weekindextuple = season.weeks .orderby(w => w.weekstarts) .select((week, index) => new { week = week, index = index }) .firstordefault(a => a.week.id == id); if(weekindextuple != null) { return weekindextuple.index; } else { // i'm not sure how want continue in case. ... }
Comments
Post a Comment