集合排序:使用默认比较器Comparable<T>排序对象


1
using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Demo 8 { 9 class Student:IComparable<Student> 10 { 11 12 public Student(int StudentId,string StudentName) 13 { 14 this.StudentId = StudentId; 15 this.StudentName = StudentName; 16 } 17 public string StudentName { get; set; } 18 public int StudentId { get; set; } 19 20 //方法:获取学员信息 21 public string GetStudent() 22 { 23 string info = string.Format("姓名:{0} 学号:{1}",StudentName,StudentId); 24 25 return info; 26 } 27 28 public int CompareTo(Student other) 29 { 30 return other.StudentId.CompareTo(this.StudentId); 31 } 32 } 33 }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

#region if运用
namespace Demo { class Program { static void Main(string[] args) { //创建几个学员变量 Student objStu1 = new Student(1001,"小王"); Student objStu2 = new Student(1002,"小张"); Student objStu3 = new Student(1003,"小李"); List<Student> stuList = new List<Student>() {objStu1,objStu2,objStu3 }; stuList.Sort(); foreach (Student stu in stuList) { Console.WriteLine(stu.StudentId+"\t"+stu.StudentName); } Console.ReadLine(); } } } #endregion

 如果是对象类型元素,当排序只有一种的时候,可使用默认比较器comparable<T>在类中直接实现接口即可。

转载于:https://www.cnblogs.com/Linglinlin/p/7149044.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值