自定义sort三种用法
1 使用接口IComparable
2 使用委托回调和lambad表达式
3 使用接口IComparer
我们先定义一个学生类
public class Student
{
//学生的编码
public int Id { get; set; }
//学生的年龄
public int Age { get; set; }
}
排序规则
1 ID小的排前面
2 ID相同的,Age小的排前面
第一种(实现IComparable接口)
public class Student : IComparable<Student>
{
//学生的编码
public int Id { get; set; }
//学生的年龄
public int Age { get; set; }
//排序规则
public int CompareTo(Student other)
{
if (Id != other.Id) return Id.CompareTo(other.Id);
return Age.CompareTo(other.Age);
}
}
完整代码
using System;
using System.Collections.Generic;
namespace SortDemo
{
class Program
{
static void Main()
{
List<Student> students = new()
{
new(){Id = 2, Age = 16},
new(){Id = 1, Age = 18},
new(){Id = 1, Age = 12}
};
students.Sort();
foreach (var item in students)
{
Console.WriteLine("ID : " + item.Id);
Console.WriteLine("Age: " + item.Age);
}
}
}
public class Student : IComparable<Student>
{
//学生的编码
public int Id { get; set; }
//学生的年龄
public int Age { get; set; }
//排序规则
public int CompareTo(Student other)
{
if (Id != other.Id) return Id.CompareTo(other.Id);
return Age.CompareTo(other.Age);
}
}
}
第二种(使用委托)
用法
//使用lambad表达式
students.Sort((a, b) =>
{
if (a.Id != b.Id) return a.Id.CompareTo(b.Id);
return a.Age.CompareTo(b.Age);
});
完整代码
using System;
using System.Collections.Generic;
namespace SortDemo
{
class Program
{
static void Main()
{
List<Student> students = new()
{
new(){Id = 2, Age = 16},
new(){Id = 1, Age = 18},
new(){Id = 1, Age = 12}
};
students.Sort((a, b) =>
{
if (a.Id != b.Id) return a.Id.CompareTo(b.Id);
return a.Age.CompareTo(b.Age);
});
foreach (var item in students)
{
Console.WriteLine("ID : " + item.Id);
Console.WriteLine("Age: " + item.Age);
}
}
}
public class Student
{
//学生的编码
public int Id { get; set; }
//学生的年龄
public int Age { get; set; }
}
}
第三种(使用接口IComparer)
实现一个StudentSort类
public class StudentSort : IComparer<Student>
{
public int Compare(Student x, Student y)
{
if (x.Id != y.Id) return x.Id.CompareTo(y.Id);
return x.Age.CompareTo(y.Age);
}
}
完整代码
using System;
using System.Collections.Generic;
namespace SortDemo
{
class Program
{
static void Main()
{
List<Student> students = new()
{
new(){Id = 2, Age = 16},
new(){Id = 1, Age = 18},
new(){Id = 1, Age = 12}
};
IComparer<Student> comparer = new StudentSort();
students.Sort(comparer);
foreach (var item in students)
{
Console.WriteLine("ID : " + item.Id);
Console.WriteLine("Age: " + item.Age);
}
}
}
public class Student
{
//学生的编码
public int Id { get; set; }
//学生的年龄
public int Age { get; set; }
}
public class StudentSort : IComparer<Student>
{
public int Compare(Student x, Student y)
{
if (x.Id != y.Id) return x.Id.CompareTo(y.Id);
return x.Age.CompareTo(y.Age);
}
}
}
结果
谢谢大家的观看0.0