C#学习笔记(28)——委托排序(2)自定义排序

说明(2017-11-21 15:24:50):

1. 定义一个排序方法,参数是字符串数组,和委托。MySort(nums, string.Compare),调用时只需要更换里面的委托方法就行,或者直接里面用Lambda表达式。

2. 这个其实是为了引出下一节的匿名委托和Lambda表达式。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace _04_委托排序
 7 {
 8     class Program
 9     {
10         #region myregion
11         public delegate int MyDel(string s1, string s2);
12         static void Main(string[] args)
13         {
14             string[] nums = "600,1,88,10,100,22,200,3,130,8".Split(',');
15             //按字符排
16             MySort(nums, string.Compare);
17             //按数字大小排,相当于下面的numCompare方法
18             MySort(nums, (a, b) => Convert.ToInt32(a) - Convert.ToInt32(b));
19             //按长度排
20             MySort(nums, (a, b) => a.Length - b.Length);
21             Console.ReadKey();
22         }
23         #endregion
24         //按照数字大小排序
25         public static int numCompare(string n1, string n2)
26         {
27             return Convert.ToInt32(n1) - Convert.ToInt32(n2);
28         }
29         //定义一个排序方法,参数是字符串数组,和委托
30         public static void MySort(string[] nums, MyDel myDel)
31         {
32             for (int i = 0; i < nums.Length; i++)
33             {
34                 for (int j = 0; j < nums.Length - i - 1; j++)
35                 {
36                     if (myDel(nums[j], nums[j + 1]) > 0)
37                     {
38                         string a = nums[j];
39                         nums[j] = nums[j + 1];
40                         nums[j + 1] = a;
41                     }
42                 }
43             }
44         }
45     }
46 }
原文地址:https://www.cnblogs.com/Jacklovely/p/7873400.html