Sorting a List in C# using List.Sort(Comparison<T> comparison
You can write lambda expression comparing two objects like this:
sm.Sort((x,y)=>x.num_of_words.CompareTo(y.num_of_words));
you can inverse sorting adding -
sm.Sort((x,y)=>-x.num_of_words.CompareTo(y.num_of_words));
You can use Linq OrderBy method for that -
sm = sm.OrderBy(i => i.num_of_words).ToList();
There is a usage example on the official microsoft documentation. The example uses strings. Replace with int
for your use.
private static int CompareDinosByLength(string x, string y)
{
...
}
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("");
dinosaurs.Add(null);
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Sort(CompareDinosByLength);
A little google goes a long way.