http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 9331|回复: 6

[C#语言基础] C#数组排序以及比较对象的大小

[复制链接]
发表于 2014-1-18 11:52:44 | 显示全部楼层 |阅读模式
C#数组排序以及比较对象的大小
先来看个小例子吧
[C#] 纯文本查看 复制代码
int[] intArray = new int[]{2,3,6,1,4,5};
Array.Sort(intArray);
Array.ForEach<int>(intArray,(i)=>Console.WriteLine(i));

这个例子定义了一个int数组,然后使用Array.Sort(arr)静态方法对此数组进行排序,最后输出排序后的数组。以上例子将毫无意外的依次输出1,2,3,4,5,6.

为什么Array的Sort方法可以正确的对int数组进行排序呢,我们自定义类可以吗?试试看,如下代码:

[C#] 纯文本查看 复制代码
public class Student 
{
    public int Age { get; set; }
 
    public string Name { get; set; }
 
    public int Score { get; set; }
}
 
 
 
static void Main(string[] args)
{
    Student[] students = new Student[]{
        new Student(){Age = 10,Name="张三",Score=70},
        new Student(){Age = 12,Name="李四",Score=97},
        new Student(){Age = 11,Name="王五",Score=80},
        new Student(){Age = 9,Name="赵六",Score=66},
        new Student(){Age = 12,Name="司马",Score=90},
    };
 
    Console.WriteLine("--------------默认排序输出--------");
    Array.Sort(students);
    Array.ForEach<Student>(students,(s)=>Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}",s.Name,s.Age,s.Score)));
 
    Console.Read();
}

我们定义了Student类然后同样对他的数组进行排序,程序正确的编译通过,但是运行出错,运行时抛出了异常:System.InvalidOperationException{"Failed to compare two elements in the array."},这个异常的InnerException是ArgumentException{"At least one object must implement IComparable."};运行时异常说明:我们要使用Array.Sort(arr)静态方法,必须得保证数组中有一个元素实现IComparable接口。既然如此我们就让Student类实现IComparable接口.

[C#] 纯文本查看 复制代码
public class Student :IComparable
{
    public int Age { get; set; }
 
    public string Name { get; set; }
 
    public int Score { get; set; }
 
 
    /// <summary>
    /// 实现IComparable接口,用Age做比较
    /// </summary>
    /// <param name="obj">比较对象</param>
    /// <returns>比较结果</returns>
    public int CompareTo(object obj)
    {
        if (obj is Student)
        {
           return Age.CompareTo(((Student)obj).Age);
        }
 
        return 1;
    }
}

在Student类中实现了IComparable接口,在CompareTo方法中比较Student的Age属性,这一次再次编译运行,程序正常的输出了按照年龄排序的Student数组。

假如说我们要对Student的Score属性进行排序该怎么办呢? Student类实现的IComparable接口只能按照一种属性排序呀。

这个是很容易实现的.net的类库开发者早为我们准备了另一个接口IComparer<T>接口用来实现比较类型T的两个实例。如下StudentScoreComparer类实现了对Student按照Score属性比较的IComparer<Student>

[C#] 纯文本查看 复制代码
public class StudentScoreComparer : IComparer<Student>
{
    public int Compare(Student x, Student y)
    {
        return x.Score.CompareTo(y.Score);
    }
}

现在我们可以使用下面代码对Student数组按照Score属性进行排序:

[C#] 纯文本查看 复制代码
Console.WriteLine("----------按分数排序输出------------");
Array.Sort(students, new StudentScoreComparer());
Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score)));

不过一个简单的按照Score属性排序,再定义一个类是不是有点大题小作呀,有没有更好的办法呢?当然有. .net为我们准备了比较对象大小的委托Comparison<T>我们可以使用拉姆达表达式或者匿名委托直接排序,如下代码实现:

[C#] 纯文本查看 复制代码
Console.WriteLine("----------按分数排序输出----------");
Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score)));

完整代码示例如下:

[C#] 纯文本查看 复制代码
using System;[/size][/font][/backcolor][/color][/p]using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SortingInCSharp
{
    class Program
    {
        public class Student : IComparable
        {
            public int Age { get; set; }
 
            public string Name { get; set; }
 
            public int Score { get; set; }
 
            /// <summary>
            /// 实现IComparable接口,用Age做比较
            /// </summary>
            /// <param name="obj">比较对象</param>
            /// <returns>比较结果</returns>
            public int CompareTo(object obj)
            {
                if (obj is Student)
                {
                    return Age.CompareTo(((Student)obj).Age);
                }
 
                return 1;
            }
        }
 
        static void Main(string[] args)
        {
            Student[] students = new Student[]{
                new Student(){Age = 10,Name="张三",Score=70},
                new Student(){Age = 12,Name="李四",Score=97},
                new Student(){Age = 11,Name="王五",Score=80},
                new Student(){Age = 9,Name="赵六",Score=66},
                new Student(){Age = 12,Name="司马",Score=90},
            };
 
            Console.WriteLine("--------------默认排序输出--------");
            Array.Sort(students);
            Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score)));
 
            Console.WriteLine("----------按分数排序输出------------");
            Array.Sort(students, new StudentScoreComparer());
            Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score)));
 
            Console.WriteLine("----------按分数排序输出----------");
            Array.Sort(students, (s1, s2) => s1.Score.CompareTo(s2.Score));
            Array.ForEach<Student>(students, (s) => Console.WriteLine(string.Format("{0}{1,2}岁了,他的分数是{2,3}", s.Name, s.Age, s.Score)));
 
 
            Console.Read();
        }
 
        public class StudentScoreComparer : IComparer<Student>
        {
            public int Compare(Student x, Student y)
            {
                return x.Score.CompareTo(y.Score);
            }
        }
    }
}

总结:

在C#中有三个关于比较对象大小的接口,分别是IComparable、IComparable<T>和IComparer<T>。 IComparable和IComparable<T>是类本身实现的在实例之间比较大小的行为定义。IComparer<T>是定义在被比较类之外的专门比较两个T类型对象大小的行为,另外还有一个用于比较的委托定义Comparison<T>可以让我们用拉姆达表达式或者匿名委托或方法更方便的排序。




1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
发表于 2014-4-2 17:22:25 | 显示全部楼层
受教了,学习中…… 占位,留待后续学习。
发表于 2014-5-24 23:23:07 | 显示全部楼层
学习了,这个非常有用!
发表于 2014-8-11 18:01:08 | 显示全部楼层
工作中会用到
发表于 2014-9-23 22:15:05 | 显示全部楼层
实现了ICompare接口,便可以使用Sort框架。
发表于 2016-6-16 17:07:45 | 显示全部楼层
[数组] C#数组排序以及比较对象的大小
学习完毕,基本理解,
发表于 2016-9-21 10:54:46 | 显示全部楼层
强烈支持楼主ing……
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-4-26 04:12

© 2014-2021

快速回复 返回顶部 返回列表