集合内的简单排序
2014-08-22 13:11
351 查看
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace Csharp { class Program { class Person:IComparable { public int Age; public int IQ; public string Name; public Person(string name, int age) { Name = name; Age = age; } //implement IComparable public int CompareTo(object obj) { if (obj is Person) { Person otherPerson = obj as Person; return this.Age - otherPerson.Age; } else throw new ArgumentException( "The things we compare is not two person"); } } class CompareByName:IComparer { //implement IComparer public static IComparer Default = new CompareByName(); public int Compare(object person1, object person2) { if (person1 is Person && person2 is Person) return Comparer.Default.Compare( ((Person)person1).Name, ((Person)person2).Name); else throw new ArgumentException( "There is something not Person"); } } static void Main(string[] args) { ArrayList persons = new ArrayList(); persons.Add(new Person("Ian", 21)); persons.Add(new Person("Rose", 18)); persons.Add(new Person("Briney", 23)); persons.Sort(); //Sort by Age foreach (Person person in persons) Console.WriteLine("{0}", person.Name); persons.Sort(CompareByName.Default); //Sort by Name foreach (Person person in persons) Console.WriteLine("{0}", person.Name); Console.ReadKey(); } } }
相关文章推荐
- 最简单的List集合排序方法
- comparator的简单学习(集合排序)
- 堆栈、队列与自动排序集合简单测试事例
- List<T>集合的Sort自定义排序用法简单解析
- 集合排序的简单解决方案
- 最简单的List集合排序方法
- java的set集合简单排序
- wpf 导出Excel Wpf Button 样式 wpf简单进度条 List泛型集合对象排序 C#集合
- 写了一个对象集合排序的类
- 关于GridView中自定义分页、单选、多选、排序、自增列的简单应用
- 关于VS2005中GridView的自定义分页,单选、多选、排序、自增列的简单应用
- 关于VS2005中GridView的自定义分页,单选、多选、排序、自增列的简单应用
- 一个简单的排序
- 简单的table列头排序
- ASP.NET小代码集合一(简单)
- 关于VS2005中GridView的自定义分页,单选、多选、排序、自增列的简单应用
- 关于GridView中自定义分页、单选、多选、排序、自增列的简单应用
- 关于VS2005中GridView的自定义分页,单选、多选、排序、自增列的简单应用
- [js].net中表格数据的排序的js应用,非常简单(中国铁路查询)
- 用IComparable来实现可排序的集合