c# - Linq Sorting not working as expected. Pretty confusing -
i have been juggling around basic thing here. have class here this:
public class linqitem { public int id { get; set; } public int accountnumber { get; set; } public double value { get; set; } public int year { get; set; } public int gifts { get; set; } public int firstyear { get; set; } public double largestyear { get; set; } public int monthgiving { { return gifts > 5 ? gifts : 0; } } } i have code returns collection of linqitem type. here code.
list<linqitem> items = loadcsv(); //some code produce collection. no problem till point, don't think loadcsv function required @ all. list<linqitem> newitems = items .orderbydescending(c => c.largestyear) .thenby(c => c.accountnumber) .thenby(c => c.year).tolist(); now, in above line, trying sort collection first largestyear descending, , order account number ascending , year ascending.
after sorting, creating csv file output. whole function looks this:
private void createcsv(string csvfile) { list<linqitem> items = loadcsv(); list<linqitem> newitems = items.orderbydescending(c => c.largestyear).thenby(c => c.accountnumber).thenby(c => c.year).tolist(); stringbuilder text = new stringbuilder(); int index = 1; foreach (linqitem in newitems) { text.appendline(i.accountnumber + "," + i.year + "," + i.value + "," + i.gifts + "," + index + "," + i.firstyear + "," + i.largestyear); index++; } streamwriter w = new streamwriter(csvfile); w.write(text.tostring()); w.close(); } now, far, pretty simple. problems when in csv, largest year values different account number same. ideally, expect if largest year same, items sorted on basis of account number , year. not happening. see following screenshot:

in screenshot, column account number, column b year, , column g largest year. , in ideal world, , sorting assumptions, assume 101864 (cell a6303) should come before 103816 (cell a6297) because sorted account number ascending. have idea?
Comments
Post a Comment