Reputation: 449
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
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
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
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
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
Reputation: 7478
You can use Linq OrderBy method for that -
sm = sm.OrderBy(i => i.num_of_words).ToList();
Upvotes: 32