C# 数组排序

来源:互联网 发布:下载苹果软件 编辑:程序博客网 时间:2024/05/16 19:26

如果要直接调用C#数组的Sort()方法对数组进行排序(如:Array.Short();list.Short().....),则必须要存储在数组中的对象实现IComparable或IComparable<T>接口,并实现CompareTo方法来指定用于排序的字段。比如实现了IComparable接口的System.String类就可以直接进行排序:

string[] strs={"aaa","cccc","bbbb"};Array.Short(strs);
如果要实现对数据实体对象的排序,则需要自己实现IComparable或IComparable<T>接口:

 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;  } } 

默认的我们可以调用:

List<Student> mouses = new List< Student > ();mouses.Short();
这样默认的就会按照Age字段值来排序。如果你需要用来排序的字段不确定,可以向Short()方法传入委托参数Comparison<T>:

mouses.Sort(delegate(Student a, Student b) { return a.Age.CompareTo(b.Age); });
委托的拉姆达形式(等效于上面的委托)这个方式灵活又方便,想对哪个字段排序就对哪个字段排序:

mouses.Sort ((m1, m2) => m1.Name.CompareTo (m2.Name));//mouses.Sort ((Mouse x, Mouse y) => x.Name.CompareTo (y));

还可以实现泛型接口IComparer<T>:

<span style="color:#111111;">using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompare{    class StudentCompare :IComparer<Student>    {        public int Compare(Student a, Student b)        {            return a.Age.CompareTo(b.Age);        }    }}using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace GenericCompare{    class Program    {        static void Main(string[] args)        {            List<Student> students = new List<Student>();            students.Add(new Student("001","kenshincui",25));            students.Add(new Student("002", "miaoer", 23));            students.Add(new Student("003", "shenjinjuan", 22));            students.Add(new Student("004", "nieyanxin", 24));            Console.WriteLine("未进行排序之前:");            foreach (Student st in students)            {                Console.WriteLine(st.No+","+st.Name+","+st.Age+";");            }            Console.WriteLine("List.Sort (泛型 IComparer) 排序之后:");            </span><span style="color:#ff0000;">students.Sort(new StudentCompare());</span><span style="color:#111111;">            foreach (Student st in students)            {                Console.WriteLine(st.No + "," + st.Name + "," + st.Age + ";");            }            Console.ReadKey();        }    }}</span>
冒泡排序:

   int temp = 0;    for (int i = list.Count; i > 0; i--)    {        for (int j = 0; j < i - 1; j++)        {            if (list[j] > list[j + 1])            {                temp = list[j];                list[j] = list[j + 1];                list[j + 1] = temp;            }        }    }





0 0
原创粉丝点击