13.集合中对象的默认排序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _3.集合中对象的默认排序
{
class Program
{
static void Main(string[] args)
{
//////////1.字符串排序
List
{
"小王","小李","小赵","小顺","小孙","小刘","小红","小唐","小阿","小夏"
};
Console.WriteLine("-----------string排序前----------");
foreach (string item in list)
{
Console.WriteLine(item);
}
Console.WriteLine("-----------string排序后----------");
list.Sort();//直接排序元素
foreach (string item in list)
{
Console.WriteLine(item);
}
Console.WriteLine("---------string排序后反转--------------");
list.Reverse();
foreach (string item in list)
{
Console.WriteLine(item);
}
////////////////////2.值类型排序
List<int> list_int = new List<int>()
{
20,21,67,18,62,82,20
};
Console.WriteLine("-----------list_int排序前---------------");
foreach (int item in list_int)//遍历
{
Console.WriteLine(item);
}
Console.WriteLine("-----------list_int排序后---------------");
list_int.Sort();//调用Sort()方法直接排序元素
foreach (int item in list_int)
{
Console.WriteLine(item);
}
Console.WriteLine("-----------list_int排序后反转-----------------");
list_int.Reverse();
foreach (int item in list_int)
{
Console.WriteLine(item);
}
///////////2.对象的排序
//对象要考虑用什么来排序!!!!!
//下面用学号来排序。还可以用学生姓名来排序。考虑一下。
Student obj1 = new Student(100, "小王");
Student obj2 = new Student(108, "小夏");
Student obj3 = new Student(102, "小刘");
Student obj4 = new Student(103, "小张");
List<Student> listStu = new List<Student>() { obj1,obj2,obj3,obj4};
Console.WriteLine("------------Student对象排序前-----------");
foreach (Student item in listStu)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentNmae + "\t" + item.Age);
}
Console.WriteLine("------------Student对象排序后-----------");
listStu.Sort();
foreach (Student item in listStu)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentNmae + "\t" + item.Age);
}
Console.WriteLine("------------Student对象排序后反转-----------");
listStu.Reverse();
foreach (Student item in listStu)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentNmae + "\t" + item.Age);
}
Console.ReadKey();
}
}
class Student : IComparable<Student> //IComparable<> 默认的泛型比较器接口
{
public Student()
{
}
public Student(Int32 stuId, string stuNmae)
{
this.StudentId = stuId;
this.StudentNmae = stuNmae;
}
public Int32 StudentId { get; set; }
public string StudentNmae { get; set; }
public Int32 Age { get; set; }
/// <summary>
/// 实现接口
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(Student other)
{
return other.StudentId.CompareTo(this.StudentId);//降序排序
// return this.StudentId.CompareTo(other);//升序排序
}
/// <summary>
/// 显示实现接口
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
//int IComparable<Student>.CompareTo(Student other)
//{
// throw new NotImplementedException();
//}
}
}