首页 > 学院 > 开发设计 > 正文

C# 实现List实例中实例元素的排序

2019-11-11 05:11:32
字体:
来源:转载
供稿:网友

C# 实现List实例中实例元素的排序

实现List实例中元素的排序除了有一下两种较好的实现途径:

使需要排序的类实现IComparable<T>接口;创建需要排序的类的一个实现ICompare<T>接口的新类,将新类的实例传入到List.Sort(newOject)方法中。

代码示例:

实现IComparable接口方式using System;using System.Collections.Generic;namespace 鸭子{ internal class PRogram { private static void Main() { var ducks = new List<Duck>() { new Duck(){Kind = KindOfDuck.Musovy,Size = 17}, new Duck(){Kind = KindOfDuck.Musovy,Size = 18}, new Duck(){Kind = KindOfDuck.Decoy,Size = 14}, new Duck(){Kind = KindOfDuck.Musovy,Size = 11}, new Duck(){Kind = KindOfDuck.Mallard,Size = 14}, new Duck(){Kind = KindOfDuck.Decoy,Size = 13}, }; ducks.Sort();//鸭子排序 foreach (var duck in ducks) { Console.WriteLine(duck.Kind + " " + duck.Size); } Console.ReadKey(); } } internal class Duck : IComparable<Duck>//鸭子类实现IComparable<T>接口,实现排序功能 { public int Size; public KindOfDuck Kind; public int CompareTo(Duck other) { if (this.Size > other.Size) { return 1; } if (this.Size < other.Size) { return -1; } return 0; } } internal enum KindOfDuck { Mallard, Musovy, Decoy, }}实现ICompare接口方式using System;using System.Collections.Generic;namespace 鸭子1{ internal class Program { private static void Main() { var ducks = new List<Duck>() { new Duck(){Kind = KindOfDuck.Musovy,Size = 17}, new Duck(){Kind = KindOfDuck.Musovy,Size = 18}, new Duck(){Kind = KindOfDuck.Decoy,Size = 14}, new Duck(){Kind = KindOfDuck.Musovy,Size = 11}, new Duck(){Kind = KindOfDuck.Mallard,Size = 14}, new Duck(){Kind = KindOfDuck.Decoy,Size = 13}, }; //var compare=new DuckCompare(){SortBy = SortCriteria.SizeThenKind};//先大小后种类排序 var compare = new DuckCompare() { SortBy = SortCriteria.KindThenSize };//先种类后大小排序 ducks.Sort(compare);//鸭子排序 foreach (var duck in ducks) { Console.WriteLine(duck.Kind + " " + duck.Size); } Console.ReadKey(); } } internal class Duck { public int Size; public KindOfDuck Kind; } internal enum KindOfDuck { Mallard, Musovy, Decoy, } internal enum SortCriteria { SizeThenKind, KindThenSize, } internal class DuckCompare : IComparer<Duck>//新的鸭子类实现ICompare<T>接口,实现排序功能 { public SortCriteria SortBy=SortCriteria.SizeThenKind; public int Compare(Duck x, Duck y) { if (SortBy==SortCriteria.SizeThenKind) { if (x.Size>y.Size) { return 1; } if (x.Size<y.Size) { return -1; } if (x.Kind>y.Kind) { return 1; } if (x.Kind<y.Kind) { return -1; } return 0; } if (x.Kind > y.Kind) { return 1; } if (x.Kind < y.Kind) { return -1; } if (x.Size > y.Size) { return 1; } if (x.Size < y.Size) { return -1; } return 0; } }}

两种方式对比

IComparable<T>接口方式属于内嵌方式,要提前设计好,使用起来简单一点,灵活性就差了一点;ICompare<T>接口方式刚好相反,需要根据排序创建新的类,但是更加灵活,不用改变现有的没有排序功能的类,而且能实现复杂排序。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表