zoukankan      html  css  js  c++  java
  • C# 对排序的认识( Comparison ) ,使用匿名方法实现比较器

      在C#中对数组及集合的排序(Sort) .需要提拱一个"比较器" (一个实现 IComparer 接口的类) 也可以用一个方法做比较器 这个方法 需要返回 0 1 或 -1.

    View Code
     1 using System;
    2
    3 class ListSort
    4 {
    5 static void Main()
    6 {
    7 int[] nums = {3,6,8,1,2,9};
    8
    9 Array.Sort(nums , delegate(int i,int j){ //使用匿名方法实现 Comparison
    10 if (i == j) // 这个接口的返回值为 1 0 -1. 用来实现排序
    11 { // 这里是倒序排列
    12 return 0; //相等 返回 0
    13 }
    14 else if (i < j)
    15 {
    16 return 1;
    17 }
    18 else
    19 return -1;
    20 });
    21
    22 #region output
    23 foreach(int i in nums)
    24 Console.Write(i);
    25 Console.WriteLine();
    26 #endregion
    27 // 正序: 1 2 3 6 8 9
    28 // 倒序: 9 8 6 3 2 1
    29 }
    30 }
  • 相关阅读:
    C++ 虚成员函数和动态联编
    C++ 多态公有继承
    C++ 继承特性
    C++ 公有派生
    C++ 基类与派生类
    C++ 类继承
    C++ 伪私有方法
    C++ new失败
    mysql用户授权
    linux时间设置
  • 原文地址:https://www.cnblogs.com/easyfrog/p/2311949.html
Copyright © 2011-2022 走看看