C# Sort

There is a natural order of things. Day alternates with night. Human beings also impose order where previously there was none. Numbers and letters come one after another. All these things can be sorted. The .NET Framework provides built-in methods to sort elements from Lists and arrays.

It is tempting to try to develop ways to improve quicksort: A faster sorting algorithm is computer science's "better mousetrap," and quicksort is a venerable method that seems to invite tinkering.Sedgewick, p. 317

Char array

Array type

To start, this example program uses a character array of three chars and then calls Array.Sort on it to sort it in-place. Then, it loops through all the characters and displays the elements in their new, alphabetical order.

Program that sorts character array [C#]

using System;

class Program
{
    static void Main()
    {
	char[] array = { 'z', 'a', 'b' }; // Input array.
	Array.Sort<char>(array); // Sort array.
	foreach (var c in array)
	    Console.WriteLine(c);
    }
}

Output

a
b
z

String arrays

String array illustration

Next, we remember that the C# language and .NET Framework has several collection sorting methods and also there is LINQ query syntax. We benchmark and demonstrate the sort methods on arrays, such as Array.Sort, and Lists. For our demonstration, we show the strings we will be sorting.

String Array
Unsorted

Zimbabwe
America
India
Germany
China
Ukraine

Sorted

America
China
India
Germany
Ukraine
Zimbabwe

Array.Sort

We see how you can call the static Array.Sort method and use it to sort a string array in place. The result is an alphabetical sort. This console program demonstrates how to use the Array.Sort method.

Array.Sort
Program that uses Array.Sort [C#]

using System;

class Program
{
    static void Main()
    {
	string[] a = new string[]
	{
	    "Egyptian",
	    "Indian",
	    "American",
	    "Chinese",
	    "Filipino",
	};
	Array.Sort(a);
	foreach (string s in a)
	{
	    Console.WriteLine(s);
	}
    }
}

Output

American
Chinese
Egyptian
Filipino
Indian

Query expression

LINQ (language integrated query)

Next, we see how to take a string[] array and use a LINQ query expression to order its contents alphabetically. Note that we are ordering the strings, not the letters in the strings. You can see that the orderby keyword results in the same output as the Array.Sort method.

Program that uses LINQ [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	string[] a = new string[]
	{
	    "Indonesian",
	    "Korean",
	    "Japanese",
	    "English",
	    "German"
	};
	var sort = from s in a
		   orderby s
		   select s;

	foreach (string c in sort)
	{
	    Console.WriteLine(c);
	}
    }
}

Output

English
German
Indonesian
Japanese
Korean

Note. When you use the query expression in LINQ, it returns an IEnumerable collection. This just means it is a collection that you have to enumerate (loop over) to get with the foreach loop.

IEnumerable Foreach Loop Examples

Reverse (LINQ)

We sort strings from Z to A instead of A to Z. This is called reverse alphabetic order. LINQ here is used with a query expression that is an enumeration of the original strings ordered from Z to A.

Program that uses LINQ descending [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	string[] a = new string[]
	{
	    "French",
	    "Italian",
	    "European",
	    "Irish",
	    "Vietnamese"
	};
	var desc = from s in a
		   orderby s descending
		   select s;

	foreach (string c in desc)
	{
	    Console.WriteLine(c);
	}
    }
}

Output

Vietnamese
Italian
Irish
French
European

Description. This example is the same as in the previous example, except use different strings, and uses the descending keyword. Ascending means to go from lowest to highest (A to Z), while descending means to go from highest to lowest (Z to A).

LINQ keywords. The orderby keyword is not a method per se; it compiles into a method call. It is part of the query expression syntax form in LINQ. See the articles here for more information.

orderby ascending descending

Collections

List type.

The List and ArrayList collections both have sorting methods; we describe and provide examples for their use. If you want to sort your List or ArrayList, they may be helpful.

Sort List Method ArrayList Sort and Reverse

Sort List

List<string> indicates a generic List collection of strings. Internally, it is stored as an array, but it is not an array type in the C# language. Therefore, you have to use its separate Sort method. Also, you can use LINQ with the exact syntax on List as used on arrays. This is because both arrays and Lists implement the IEnumerable interface.

List Examples
Program that uses List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	List<string> l = new List<string>()
	{
	    "Australian",
	    "Mongolian",
	    "Russian",
	    "Austrian",
	    "Brazilian"
	};
	l.Sort();
	foreach (string s in l)
	{
	    Console.WriteLine(s);
	}
    }
}

Output

Australian
Austrian
Brazilian
Mongolian
Russian

Copy then sort

With most sort methods, the collection you call sort on is sorted in-place: this means the unsorted, original collection no longer exists. If you want to retain the original order in a parallel collection, you must first copy the elements to a new collection, as with the List constructor.

Program that sorts copy [C# .NET 4.0]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	string[] array = { "zebra", "parrot", "ant" };

	List<string> copy = new List<string>(array);
	copy.Sort();

	Console.WriteLine(string.Join(",", array));
	Console.WriteLine(string.Join(",", copy));
    }
}

Output

zebra,parrot,ant
ant,parrot,zebra

Description. The List elements are sorted, but the original array is left alone. Please note that this program requires the .NET Framework version 4.0 or later to compile because of the string.Join methods called.

String Join Method

Performance

Performance optimization

Originally, this page showed a benchmark of the sorting methods (LINQ, List.Sort, and Array.Sort) on collections of varying sizes (46, 92, and 460 elements). The performance of these methods was very close; the LINQ method were slower by a small amount.

Performance note:Because Array.Sort, List.Sort and LINQ sorting are all implemented with quicksort internally, the overall performance is going to be very similar. LINQ has a small performance overhead.

IComparable

Generic type

You can implement sorting directly on a class, and then when you try to sort a collection of that type, your custom sorting method will be used automatically. For more information, read about the IComparable<T> interface. Also the CompareTo method is covered in some detail.

IComparable Example With CompareTo CompareTo Int Method

Internals

.NET Framework information

Internally, you can see that the List sort method is implemented with Array.Sort. This is why it performs very closely to how the Array.Sort method does. To examine the internals of the List sorting method, you can open IL Disassembler and open the Sort method.

IL Disassembler Tutorial
Part of implementation of List.Sort [C#]

Array.Sort<T>(this._items, index, count, comparer);

Type specifier. The Array.Sort method shown is a generic method, which means you must specify the type when you call the method. Note that the C# compiler can derive the type implicitly in many cases. This means that Array.Sort is the same as Array.Sort<T>.

Generic Method

Characters

Continuing on, you occasionally want to alphabetize the letters in a string. We provide methods to do this. We can manipulate and rearrange characters.

Alphabetize String

Dictionary

The Dictionary collection has both keys and values, but no way to sort these that is built into the .NET Framework. You can instead acquire the Keys or Values collections and sort them. We provide tips and tricks for doing this.

Sort Dictionary Keys and Values

Reverse

Reverse graphic

To reverse an array of elements simply changes the order from back to front. It does not alphabetize or reorder the elements in an ascending or descending order. We describe how you can reverse an array of words or the characters in a string.

Reverse Words Reverse String

Custom methods

Question and answer

Do you need a sorting algorithm that treats the string "300" as greater than "31"? The alphanumeric sorting algorithm will actually parse substrings into numbers. We demonstrate its use.

Alphanumeric Sorting Sort Number Strings

Detection. Occasionally, an array of elements you need to be sorted may already be sorted. In this case, you don't need to sort it again. We demonstrate how you can detect this can and avoid the entire sort.

Sorted Array Test Method

Property sorting. Sometimes you may want to sort an array based on some characteristic of each element. You can even access the file system as the sorting method proceeds. We provide information on sorting on properties of each element.

Sort Files by Their Sizes Sort Ignore Leading Chars Example Sort KeyValuePair List Sort Strings by Length Sort Tuple List

Ignore leading chars:It is also possible to ignore some characters when you are sorting an array of strings. You can do this by using the TrimStart method on an orderby clause—more details are available.

Summary

The C# programming language

Sorting in the C# programming language is easiest done with method calls. It is important to copy your collection first if you don't want to replace it with the sorted instance. We learned that the List sort method and the Array.Sort method are implemented with the same algorithm.

C# Sort

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值