C # basic array sorting, object size comparison

Source: Internet
Author: User
Tags array sort

Starting from a small example:

View sourceprint? 1 int [] intArray = new int [] {2, 3, 6, 1, 4, 5 };

2 Array. Sort (intArray );

3 Array. ForEach <int> (intArray, (I) => Console. WriteLine (I ));

This example defines an int Array, uses the Array. Sort (arr) Static Method to Sort the Array, and finally outputs the sorted Array. In the preceding example, output 1, 2, 3, 4, 5, 6 in sequence.

Why can the Array Sort method correctly Sort the int Array? Can we use a custom class? Try the following code:

View sourceprint? 01 public class Student

02 {

03 public int Age {get; set ;}

04

05 public string Name {get; set ;}

06

07 public int Score {get; set ;}

08}

09

10

11

12 static void Main (string [] args)

13 {

14 Student [] students = new Student [] {

15 new Student () {Age = 10, Name = "James", Score = 70 },

16 new Student () {Age = 12, Name = "", Score = 97 },

17 new Student () {Age = 11, Name = "Wang Wu", Score = 80 },

18 new Student () {Age = 9, Name = "Zhao ", Score = 66 },

19 new Student () {Age = 12, Name = "Sima", Score = 90 },

20 };

21

22 Console. WriteLine ("-------------- default sorting output --------");

23 Array. Sort (students );

24 Array. forEach <Student> (students, (s) => Console. writeLine (string. format ("{0} {1, 2} years old, his score is {2, 3}", s. name, s. age, s. score )));

25

26 Console. Read ();

27}

We defined the Student class and sorted its arrays. The program was correctly compiled, but an error occurred while running. An exception was thrown: System. invalidOperationException {"Failed to compare two elements in the array. "}, the InnerException of this exception is ArgumentException {" At least one object must implement IComparable. "}; runtime exception description: we need to use Array. the Sort (arr) static method must ensure that an element in the array implements the IComparable interface. In this case, let the Student class implement the IComparable interface.

View sourceprint? 01 public class Student: IComparable

02 {

03 public int Age {get; set ;}

04

05 public string Name {get; set ;}

06

07 public int Score {get; set ;}

08

09

10 /// <summary>

11 // implement the IComparable interface and use Age for comparison

12 /// </summary>

13 // <param name = "obj"> comparison object </param>

14 /// <returns> comparison result </returns>

15 public int CompareTo (object obj)

16 {

17 if (obj is Student)

18 {

19 return Age. CompareTo (Student) obj). Age );

20}

21

22 return 1;

23}

24}

The IComparable interface is implemented in the Student class, and the Age attribute of Student is compared in the CompareTo method. During this re-compilation, the program normally outputs the Student array sorted by Age.

What if we want to sort the Score attribute of Student? The IComparable interface implemented by the Student class can only be sorted by one attribute.

This is easy to implement. net class library developers have prepared another IComparer <T> interface for us to implement two instances of the comparison type T. The following StudentScoreComparer class provides IComparer for Student to compare the Score attributes. <Student>

View sourceprint? 1 public class StudentScoreComparer: IComparer <Student>

2 {

3 public int Compare (Student x, Student y)

4 {

5 return x. Score. CompareTo (y. Score );

6}

7}

Now we can use the following code to sort the Student array by the Score attribute:

View sourceprint? 1 Console. WriteLine ("---------- sorting by score output ------------");

2 Array. Sort (students, new StudentScoreComparer ());

3 Array. forEach <Student> (students, (s) => Console. writeLine (string. format ("{0} {1, 2} years old, his score is {2, 3}", s. name, s. age, s. score )));

However, it is a little difficult to simply sort by Score attributes and define a class. Is there a better way? Of course, the. net delegate for us to compare the object size Comparison <T> we can use the lambda expression or anonymous delegate to directly sort, the following code is implemented:

View sourceprint? 1 Console. WriteLine ("---------- output by scores ----------");

2 Array. Sort (students, (s1, s2) => s1.Score. CompareTo (s2.Score ));

3 Array. forEach <Student> (students, (s) => Console. writeLine (string. format ("{0} {1, 2} years old, his score is {2, 3}", s. name, s. age, s. score )));

The complete code example is as follows:

Show sourceview sourceprint? 01 using System;

02 using System. Collections. Generic;

03 using System. Linq;

04 using System. Text;

05

06 namespace SortingInCSharp

07 {

08 class Program

09 {

10 public class Student: IComparable

11 {

12 public int Age {get; set ;}

13

14 public string Name {get; set ;}

15

16 public int Score {get; set ;}

17

18 /// <summary>

19 // implement the IComparable interface and use Age for comparison

20 /// </summary>

21 /// <param name = "obj"> comparison object </param>

22 /// <returns> comparison result </returns>

23 public int CompareTo (object obj)

24 {

25 if (obj is Student)

26 {

27 return Age. CompareTo (Student) obj). Age );

28}

29

30 return 1;

31}

32}

33

34 static void Main (string [] args)

35 {

36 Student [] students = new Student [] {

37 new Student () {Age = 10, Name = "James", Score = 70 },

38 new Student () {Age = 12, Name = "", Score = 97 },

39 new Student () {Age = 11, Name = "Wang Wu", Score = 80 },

40 new Student () {Age = 9, Name = "Zhao ", Score = 66 },

41 new Student () {Age = 12, Name = "Sima", Score = 90 },

42 };

43

44 Console. WriteLine ("-------------- default sorting output --------");

45 Array. Sort (students );

46 Array. forEach <Student> (students, (s) => Console. writeLine (string. format ("{0} {1, 2} years old, his score is {2, 3}", s. name, s. age, s. score )));

47

48 Console. WriteLine ("---------- sort by score output ------------");

49 Array. Sort (students, new StudentScoreComparer ());

50 Array. forEach <Student> (students, (s) => Console. writeLine (string. format ("{0} {1, 2} years old, his score is {2, 3}", s. name, s. age, s. score )));

51

52 Console. WriteLine ("---------- output by scores ----------");

53 Array. Sort (students, (s1, s2) => s1.Score. CompareTo (s2.Score ));

54 Array. forEach <Student> (students, (s) => Console. writeLine (string. format ("{0} {1, 2} years old, his score is {2, 3}", s. name, s. age, s. score )));

55

56

57 Console. Read ();

58}

59

60 public class StudentScoreComparer: IComparer <Student>

61 {

62 public int Compare (Student x, Student y)

63 {

64 return x. Score. CompareTo (y. Score );

65}

66}

67}

68}

Summary:

In C #, there are three interfaces for comparing object sizes: IComparable, IComparable <T>, and IComparer <T>. IComparable and IComparable <T> are behavior definitions implemented by the class itself to compare the size between instances. IComparer <T> is a behavior that defines the size of two T-type objects outside the compared class, another delegate definition for Comparison is Comparison <T>, which allows us to use lambda expressions or anonymous delegates or methods for easier sorting.

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.