c#中实现对象集合的排序可以使用ArrayList中的Sort()方法,而有比较才能谈排序,因为不是基本类型(如string ,int.double......等)所以.NET Framework不可能一一制定他们的比较规则,那么则需要程序员自行制定,而比较规则的制定就需要通过继承这两个接口>之一来实现。制定了比较规则后则才可以用以下两种方式之一调用排序:

(1)ArrayList实例.Sort(); // IComparable

(2)ArrayList实例.Sort(实现Icomparer接口的类); // Icomparer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections; namespace Demo3
{
class Program
{
static void Main(string[] args)
{
//新建集合people用来存放person实例
ArrayList people = new ArrayList();
//建立4个person实例
Person person1 = new Person("Jone", 18);
Person person2 = new Person("Tom", 20);
Person person3 = new Person("Lily", 15);
Person person4 = new Person("July", 25);
//将实例添加到people集合中
people.Add(person1);
people.Add(person2);
people.Add(person3);
people.Add(person4);
//输出原来序列
Console.WriteLine("原来序列:");
foreach (Person person in people)
{
Console.WriteLine("person name: {0} age:{1}", person.Name, person.Age);
}
//用实现Icomparable进行排序
people.Sort();
//用实现Icomparable的方法输出排序后的序列
Console.WriteLine("按年龄排序后的序列:");
foreach (Person person in people)
{
Console.WriteLine("person name: {0} age:{1}", person.Name, person.Age);
}
//用实现Icomparer的方法进行排序
people.Sort(PersonComparer.Default);
//用实现Icomparer的方法输出排序后的序列
Console.WriteLine("按名称排序后的序列:");
foreach (Person person in people)
{
Console.WriteLine("person name: {0} age:{1}", person.Name, person.Age);
}
Console.ReadKey();
}
} public class Person : IComparable
{
/// <summary>
/// 两个私有字段:
/// 人物姓名;
/// 人物年龄;
/// </summary>
private string name;
private int age; /// <summary>
/// 构造函数
/// </summary>
public Person(string myname, int myage)
{
name = myname;
age = myage;
} /// <summary>
/// 两个共有属性:
/// 分别对应两个私有字段;
/// </summary>
public string Name
{
set
{
name = value;
}
get
{
return name;
}
}
public int Age
{
set
{
age = value;
}
get
{
return age;
}
} public int CompareTo(object myobject)
{
if (myobject is Person)//用is运算符判断要比较的对象是否是Person对象
{
//如果是用as运算符进行对象转换,返回年龄比较结果(一个整数,表示两者差)
Person myperson = myobject as Person;
return this.Age - myperson.Age;
//return myperson.Age - this.Age;
}
else
{
//如果不是,抛出异常
throw new ArgumentException("Object to compare to is not a Person Object");
}
}
} public class PersonComparer : IComparer
{
//静态字段,方便使用,没有也可,调用方法会变
public static IComparer Default = new PersonComparer();
public int Compare(object myperson1, object myperson2)
{
//用is运算符判断要比较的对象是否都是Person对象
if (myperson1 is Person && myperson2 is Person)
{
//如果是,调用.Net Framework已经实现好的能比较基本类型的函数:Comparer.Default.Compare
//(要用using System.Collections;)
return Comparer.Default.Compare(((Person)myperson1).Name, ((Person)myperson2).Name);
}
else
{
//如果不是抛出异常
throw new ArgumentException("One or both objects to compare are not Person objects.");
}
}
}
}

方法论:读书加上网查询相关资料,能够更好的理解知识点。

Icomparer和Icomparable集合排序的更多相关文章

  1. C# List.Sort与IComparer接口及Comparison委托应用于集合排序

    C#里List.Sort的用法 using System; using System.Collections.Generic; using System.Linq; using System.Text ...

  2. .NET Framework System.Array.Sort 数组类,加深对 IComparer、IComparable 以及泛型委托、匿名方法、Lambda 表达式的理解

    本文内容 自定义类 Array.Sort 参考资料 System.Array.Sort 有很多对集合的操作,比如排序,查找,克隆等等,你可以利用这个类加深对 IComparer.IComparable ...

  3. .Net中集合排序的一种高级玩法

    背景: 学生有名称.学号, 班级有班级名称.班级序号 学校有学校名称.学校编号(序号) 需求 现在需要对学生进行排序 第一排序逻辑 按学校编号(序号)排列 再按班级序号排列 再按学生学号排列 当然,在 ...

  4. 通过写一个Demo展示C#中多种常用的集合排序方法

    不多说,程序很简单,就是将集合中的数据进行排序,但使用到的知识点还是比较多的,大牛勿喷,谨献给初学者!直接上程序吧! namespace Demo { /// <summary> /// ...

  5. Java比较器对数组,集合排序一

    数组排序非常简单,有前辈们的各种排序算法,再加上Java中强大的数组辅助类Arrays与集合辅助类Collections,使得排序变得非常简单,如果说结合比较器Comparator接口和Collato ...

  6. ArrayList集合排序

    using System;using System.Collections;using System.Collections.Generic;using System.Text; namespace ...

  7. 【Java进阶】---map集合排序

    map集合排序         这篇文章讲的不仅仅是map排序,比如把对象按某一属性排序,它都可以解决这些问题.   比如,有N个对象,每个对象有个属性就是成绩,成绩分:优秀,良好,合格.那我们如何按 ...

  8. CopyOnWriteArrayList集合排序异常问题

    1.集合自定义排序实现 对List集合的自定义排序想必大家都知道要使用如下的方式,通过实现Comparator接口并实现compare方法来实现. /** * * @方法名 changeChain * ...

  9. 二维码扫描&集合排序

    一.二维码扫描机制 二维条码/二维码(2-dimensional bar code)是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的:在代码编制上巧妙地利用构 ...

随机推荐

  1. iOS菜鸟成长笔记(2)——网易彩票练习

    距离上一篇<第一个iOS应用>已经有一个多月了,今天来和大家一起学习和分享一下一个小练习<网易彩票> 首先我们向storyboard中拖入一个TabBarController和 ...

  2. NestedScrollView嵌套ListView可行性总结

    由于公司项目遗留代码仍然使用PullToRefreshListView(后文简称PTRLV),且存在复用,更换RecyclerView成本太大,同时又想使用CoordinatorLayout来实现一些 ...

  3. 51Nod 天堂里的游戏

    多年后,每当Noder看到吉普赛人,就会想起那个遥远的下午. Noder躺在草地上漫无目的的张望,二楼的咖啡馆在日光下闪着亮,像是要进化成一颗巨大的咖啡豆.天气稍有些冷,但草还算暖和.不远的地方坐着一 ...

  4. FlatternMap和Map的区别

    flattenMap使用步骤:     1.传入一个block,block类型是返回值RACStream,参数value     2.参数value就是源信号的内容,拿到源信号的内容做处理     3 ...

  5. mac本 maven项目还没发布成功,tomcat就报没有监听ContextLoaderListener 的解决方法

    Maven项目下update maven后Eclipse报错:java.lang.ClassNotFoundException: ContextLoaderL     严重: Error config ...

  6. DAG-背包九解-01背包

    饭卡:   电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额.如果购买一个商品之前,卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够 ...

  7. caffe(1) 网络结构层参数详解

    prototxt文件是caffe的配置文件,用于保存CNN的网络结构和配置信息.prototxt文件有三种,分别是deploy.prototxt,train_val.prototxt和solver.p ...

  8. [USACO08DEC]拍头Patting Heads 水题

    类似素数筛,暴力可过,不需要太多的优化 Code: #include<cstdio> #include<algorithm> #include<string> us ...

  9. twig 模板引擎使渲染视图更加优雅

    在使用 laravel 的时候接触过 blade 模板引擎.在学习的时候,接触到了另外一个强大的模板引擎:twig 官网:https://twig.sensiolabs.org/ 中文手册:http: ...

  10. [Python] Plotting multiple stocks

    import os import pandas as pd import matplotlib.pyplot as plt def test_run(): start_date='2017-01-01 ...