Fun<>, anonymous method, lambda expression bubble sort C #

Source: Internet
Author: User

Big Head Text

Share, progress

Bubbling sort C # implementation, using delegates, consists of three ways: fun<>, anonymous method, lambda expression

Bubble sorting is a simple sorting method, suitable for small numbers, and a more efficient sorting method for large numbers (more than 10).
Here the implementation of the bubbling sort, the need to implement the function:
Not only the number sort, but also any object sort

Example:

    • Sort age (Ages) for people objects
    • Sort the score (fractions) of the student object

People:

    Publicclass People {PublicString Name {Getset;} public int Age {get; set; } public people (string name, int age) {name = name; Age = age; } public static bool compareage (People p1, people p2) {return p1. Age < P2. Age; } public override string tostring () {return string. Format ( "[People] name:{0},age:{1}", name, age);}}  

Student:

    PublicClass Student {PublicString Name {GetSet }public float score {get; set; } public student (string name, float score) {name = name; Score = score; } public static bool comparescore (Student s1, Student S2) {return S1. Score < S2. Score; } public override string tostring () {return string. Format ( "[Student] Name:{0},score:{1}", Name,score);}}  

The implementation of the bubble sort, if the fun<> of the delegate writing do not understand, and finally there is a description.

    PublicStaticClass Storter_fun {public static void Sort<T> (Ilist<t> Sortarray, Func<t, T, bool> comparision) { bool swapped = true; do {swapped = FALSE; for (int i = 0; i < Sortarray.count-1; i++) {if (comparision (sortArray[i + 1], Sortarray[i])) {T temp = sortarray[i]; Sortarray[i] = sortarray[i + 1] ; Sortarray[i + 1] = temp; swapped = true;}} while (swapped);} }  

Console, using sort:

Staticvoid Main (string[] args) {People sort by age people[] Peoples = {New People ("Zhang San",43),New People ("John Doe",12),New People ("Harry",50),New People ("Wu Six",21),New People ("Chen Qi",33),};Fun<> commissioned by Bubblesorter.storter_fun.sort<people> (peoples, people.compareage);anonymous method notation Bubblesorter.storter_fun.sort<people> (peoples, delegate (People P1, people p2) {return P1. Age < P2. Age; });The Lambdah expression bubblesorter.storter_fun.sort<people>(Peoples, (People P1, people p2) = {return P1. Age < P2. Age; });Foreach(var peopleIn peoples) {Console.WriteLine(people); }//students sorted by scoreStudent[]Students = {NewStudent("Zhang San",80.5F),NewStudent("John Doe",85),NewStudent("Harry",88),Newstudent ( "Wu Six", 70), new student  "Chen Qi", 95),}; bubblesorter. storter_fun. sort<student> (students, Student.comparescore); foreach  (var student in students) {console. Writelineconsole. readkey ();         

Delegate: The parameters of the calling method are generally numeric, such as int,string,datatable and so on, can you pass the method itself as a parameter to another method? The Commission is to solve the problem.
Since it is a parameter, you have to have a type. C # is strongly typed, the parameter of the method is int type, cannot pass string type to go in, otherwise in the editing phase error.
Int,string is an existing type, and the type of the delegate needs to be customized.
For example, the above example is used:

    • Fun<t, t,= "" bool= "" > is represented by passing in two generic parameters, returning bool;
    • The Fun<int,string,datatable,array> delegate method is to pass in three parameters: int, string,datatable, and return an array;
      Is the last parameter is the return value type;
      So what if there is no return value?
    • The Action<t,t> method is to pass in two generic parameters without returning a value
    • The Action<int,string> method is to pass in two parameters: Int,string, no return value
      Defines the type of the delegate, the incoming method must conform to this definition, that is: incoming parameters, type, number, order, return values to be consistent, otherwise compiled, C # is a strong type reason.

The newly implemented bubbling can support the sorting of different objects, mainly by passing in the bubbling Comparison size method (delegate), and using the generic implementation for the temporary variables of exchanging data;

Category: C #

Fun<>, anonymous method, lambda expression bubble sort C #

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.