Kaushik
Kaushik

Reputation: 449

Sorting a List in C# using List.Sort(Comparison<T> comparison

I have created a class as follows:

public class StringMatch
{
   public int line_num;
   public int num_of_words;
}

I have created a list

List<StringMatch> sm;

it has few elements in it.

How do I sort this list using the Comparison<T> comparison overload? The sorting must be done based on the num_of_words field.

Upvotes: 27

Views: 55729

Answers (5)

Nayeem Bin Ahsan
Nayeem Bin Ahsan

Reputation: 471

For the mentioned list,

List<StringMatch> sm = new ();

You can sort ascending simply by,

sm.Sort((i, j) => i.num_of_words - j.num_of_words);

And descending by,

sm.Sort((i, j) => j.num_of_words - i.num_of_words);

Upvotes: 0

Kamil Budziewski
Kamil Budziewski

Reputation: 23117

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

Upvotes: 46

James
James

Reputation: 2201

Using Comparison is an older and more clunky way of sorting collections. My advice would be to use the OrderBy method found in Linq:

var orderedSm = sm.OrderBy(x => x.num_of_words).ToList();

Upvotes: 0

Gusdor
Gusdor

Reputation: 14332

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.

Upvotes: 2

Sergey Litvinov
Sergey Litvinov

Reputation: 7478

You can use Linq OrderBy method for that -

sm = sm.OrderBy(i => i.num_of_words).ToList();

Upvotes: 32

Related Questions