Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 624
Kaushik Avatar asked Jan 03 '14 11:01

Kaushik


People also ask

What is sorting array in C?

For simplicity, we will be using Selection Sort in this article. The array can be sorted in ascending order by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.

What is sorting algorithm in C?

C language provides five sorting techniques, which are as follows − Bubble sort (or) Exchange Sort. Selection sort. Insertion sort (or) Linear sort. Quick sort (or) Partition exchange sort.

How do you sort a single linked list?

Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3) Change head of given linked list to head of sorted (or result) list.

Can we sort a linked list?

Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.


Video Answer


1 Answers

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));
like image 192
Kamil Budziewski Avatar answered Oct 09 '22 10:10

Kamil Budziewski