c# - How to fix this lambda expression? -


i have function sorting multiple user selected columns:

public override void sort(sortfields sortfields) {     if (sortfields == null || sortfields.count() == 0) return;      var res = filtereditems.orderby(o => o[sortfields[0].name], sortfields[0].ascending ? comparer : comparerdesc);      (int x = 1; x < sortfields.count(); x++)         res = res.thenby(o => o[sortfields[x].name], sortfields[x].ascending ? comparer : comparerdesc);      filtereditems = new bindinglist<t>(res.tolist());      if (listchanged != null)         listchanged(this, new listchangedeventargs(listchangedtype.reset, null)); } 

the problem, of course, when res.tolist() called x has been incremented 1 greater highest index in list , throws error. know go ahead , tolist() after each sort defeats purpose , isn't guaranteed sort correctly linq providers. i'm sure there's simple solution this... want tell me is? :)

it looks may getting tripped closure on variable x.

that single variable incremented on every iteration of loop. it's incremented 1 last time, @ point it's 1 greater number of items in "sortfields", conditional statement evaluates false, , for loop ends.

as user2864740 pointed out, , eric states in article:

closures close on variables, not on values.

so when call tolist(), chained thenby statements retain final value of variable x, 1 greater highest index.

instead, assign incrementer intermediary variable inside loop. when call tolist(), final value of x won't matter.

for (int x = 1; x < sortfields.count(); x++) {     int y = x;     res = res.thenby(o => o[sortfields[y].name], sortfields[y].ascending ? comparer : comparerdesc); } 

also eric's article, (hopefully) being corrected soon, though in foreach loops apparently, not for loops:

in c# 5, loop variable of foreach logically inside loop, , therefore closures close on fresh copy of variable each time. "for" loop not changed.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -