Search code examples
c#linqlinq-to-excel

linq "let" division, then orderby ascending


I have this data, and I'm using linqToExcel: enter image description here

I'm trying to get inflation divided by GDP...then order them ascending, but I can't get it right.

    var people = from x in excel.Worksheet<CountryEconomics>("Sheet1")
                 let c = x.Inflation / x.GDP
                 orderby c ascending 
                 select c;

I'm getting the output:

12
6
4
3
2
2

no matter if I put ascending or descending in the query. How can I get the data ascending? i.e.

2
2
3
4
6
12

Solution

  • Right now, I'm just guessing, but maybe adding some casts will make it work:

    var people = from x in excel.Worksheet<CountryEconomics>("Sheet1")
                 let c = ((double)x.Inflation) / ((double)x.GDP)
                 orderby c ascending 
                 select c;
    

    However if that fails as well - what'll happen if you make it a list first:

    var people = from x in excel.Worksheet<CountryEconomics>("Sheet1").ToList()
                 let c = ((double)x.Inflation) / ((double)x.GDP)
                 orderby c ascending
                 select c;
    

    If that's still failing:

    var people = from x in excel.Worksheet<CountryEconomics>("Sheet1")
                 let c = ((double)x.Inflation) / ((double)x.GDP)
                 select c;
    
    var peopleList = people.ToList().OrderBy(p => p);
    

    Hope this gets it done...