==========================================第一种(普通排序)
string[] s = { "zhangsan", "lisi", "wangwu", "liumazi" }; Array.Sort(s);//排序 foreach (string item in s) { Console.WriteLine(item); }
==========================================第二种(自定义类排序)
------------------------Person.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { //想要自定义排序,必须实现IComparable<Person>接口 public class Person:IComparable<Person> { public string FirstName { get; set; } public string LastName { get; set; } public int CompareTo(Person other) { if (other == null)//如果传入的对象为空,则抛出异常 throw new ArgumentException("抛出异常"); int resouce = this.FirstName.CompareTo(other.FirstName);//按照FirstName排序 if (resouce == 0)//如果两个字符串一样 { resouce = this.LastName.CompareTo(other.LastName);//则按照LastName排序 } return resouce;//返回一个整形, //一个值,指示要比较的对象的相对顺序。 //返回值的含义如下: 值 含义 小于零 此实例按排序顺序在 obj 前面。 //零 此实例与 obj 在排序顺序中出现的位置相同。 // 大于零 此实例按排序顺序在 obj 后面。 } } }
------------------------Main方法
Person[] p = new Person[] { new Person { FirstName = "zhangdi", LastName = "lisi" }, new Person { FirstName = "wangwu", LastName = "zhaoliu" } }; Array.Sort(p); foreach (var pp in p) { Console.WriteLine(pp.FirstName); } Console.ReadKey();
==========================================第三种(自定义类,自定义排序)
------------------------Student.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class Student { public string FristName { get; set; } public string LastName { get; set; } } }
------------------------StuSort.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { //枚举,用于选择要按那种方式排序 public enum FirstAndLast { FristName, LastName } //想要自定义排序,必须实现IComparer<Student>接口 public class StuSort:IComparer<Student> { private FirstAndLast fal;//枚举字段 //构造函数,初始换枚举 public StuSort(FirstAndLast f) { fal = f; } public int Compare(Student x, Student y) { if (x == null || y == null)//当x或y的对象为空的时候抛出异常 throw new ArgumentException("对象不能为空"); int resouce = 0; switch (fal) { case FirstAndLast.FristName://当枚举为FirstAndLast.FristName就按FristName排序 resouce = x.FristName.CompareTo(y.FristName); break; case FirstAndLast.LastName://当枚举为FirstAndLast.LastName就按LastName排序 resouce = x.LastName.CompareTo(y.LastName); break; default: throw new ArgumentException("错误"); break; } return resouce; } } }
------------------------Main方法
Student[] s = new Student[] { new Student { FristName = "zhangdi", LastName = "aaa" }, new Student { FristName = "lisi", LastName = "bbb" }, new Student { FristName = "aa", LastName = "ccc" } }; Array.Sort(s, new StuSort(FirstAndLast.LastName)); foreach (var pp in s) { Console.WriteLine(pp.FristName); } Console.ReadKey();
本文出自 “程序猿的家” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1441125
原文地址:http://962410314.blog.51cto.com/7563109/1441125