Sort () method of Array class

Source: Internet
Author: User

I just reviewed the sort () method of the Array class. Here I will list some common ones and share them with you.

 

The Array class implements the Bubble Sorting of elements in the Array. The Sort () method requires that the elements in the array implement the IComparable interface. Such as System. Int32

And System. String implement the IComparable interface, so the following Array can use Array. Sort ().

 string[] names = { "Lili", "Heicer", "Lucy" };
Array.Sort(names);
foreach (string n in names) {
Console.WriteLine(n);
}

Output the sorted array:

 

If you use a custom class for the array, you must implement the IComparable interface. This excuse defines a method CompareTo (). <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxkaXYgY2xhc3M9 "cnblogs_code" onclick = "cnblogs_code_show (139a6c7f-4e03-446d-a73a-c588771ba92e)"> Person class

 1 public class Person: IComparable {
2 public Person (){}
3 public Person (string name, string sex ){
4 this. Name = name;
5 this. Sex = sex;
6}
7 public string Name;
8 public string Sex;
9
10 public override string ToString (){
11 return this. Name + "" + this. Sex;
12}
13 # region IComparable Member
14 public int CompareTo (object obj ){
15 Person p = obj as Person;
16 if (p = null ){
17 throw new NotImplementedException ();
18}
19 return this. Name. CompareTo (p. Name );
20}
21 # endregion
22}

Here we can sort the Person object array:

 1<

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.