1

I was wondering how I would sort this list of mine. Say i have class,

public class Foo
{
     public float bar;
}

And say I have list

List<Foo> sortedList = new List<Foo>();

And I want to sort Foo by its variable bar. I am pretty sure i should use the linQ statement orderby, but i cant figure out how to sort by a variable in a class.

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
Hexagon789
  • 315
  • 2
  • 4
  • 16

3 Answers3

1

Sort a list by calling OrderBy. Note this return an IEnumerable<T> to you will have to call ToList() to get a list again:

var list = new List<Foo>();
var sortedList = list.OrderBy(foo => foo.bar).ToList();
Anduril
  • 1,236
  • 1
  • 9
  • 33
0

One option:

var sorted =
        from foo in sortedList 
        orderby foo.bar ascending
        select foo;

Or:

var sorted = sortedList.OrderBy(foo => foo.bar);
KiwiPiet
  • 1,304
  • 14
  • 21
0

This is how I am doing it:

private List<ItemTotalsAcrossMonths> _itemTotalsAcrossMonthsList;
. . .
_itemTotalsAcrossMonthsList = _itemTotalsAcrossMonthsList.OrderByDescending(x => x.TotalPurchases13).ToList();

I'm simply assigning the results of the sort back to the generic list; you need the "ToList()" at the end.

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862