How to sort a list of a custom class by a variable in this custom class? C #


This question already has an answer here:

  • How to Sort a List<T> by a property in the object 19 answers

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.

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 =>;