using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
class Student:IComparable<Student>
{
private string Name;
private int Age;
private string City;
private int Score;
public Student(string name,int age,string city,int score)
{
this.Name = name;
this.Age = age;
this.City = city;
this.Score = score;
}
public string sname
{
get { return Name; }
}
public int sage
{
get { return Age; }
}
public string scity
{
get { return City; }
}
public int sscore
{
get { return Score; }
}
public int CompareTo (Student p)
{
return this.sscore - p.sscore;
}
} class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
List<Student> stu = new List<Student>();
Student zs = new Student("张三",18,"福州",rnd.Next(300,500));
Student ls = new Student("李四",19,"北京",rnd.Next(300,500));
Student ww = new Student("王武",19,"黑龙江",rnd.Next(300,500));
stu.Add(zs);
stu.Add(ls);
stu.Add(ww); foreach (Student i in stu)
{
Console.WriteLine(i.sname + "年龄" + i.sage + "来至于" + i.scity + "总分" + i.sscore);
}
Console.ReadKey(); }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
class Student:IComparable<Student>
{
private string Name;
private int Age;
private string City;
private int Score;
public Student(string name,int age,string city,int score)
{
this.Name = name;
this.Age = age;
this.City = city;
this.Score = score;
}
public string sname
{
get { return Name; }
}
public int sage
{
get { return Age; }
}
public string scity
{
get { return City; }
}
public int sscore
{
get { return Score; }
}
public int CompareTo (Student p)
{
return this.sscore - p.sscore;
}
} class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
List<Student> stu = new List<Student>();
Student zs = new Student("张三",18,"福州",rnd.Next(300,500));
Student ls = new Student("李四",19,"北京",rnd.Next(300,500));
Student ww = new Student("王武",19,"黑龙江",rnd.Next(300,500));
stu.Add(zs);
stu.Add(ls);
stu.Add(ww); foreach (Student i in stu)
{
Console.WriteLine(i.sname + "年龄" + i.sage + "来至于" + i.scity + "总分" + i.sscore);
}
Console.ReadKey(); }
}
}
{
...
public int CompareTo (Student p)
{
return p.sscore.CompareTo(this.sscore);
}
}
main中stu.sort();
/// <summary>
/// 按照学生的总分降序排序
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static List<Student> SortList(List<Student> list)
{
var result = from pairs in list orderby pairs.total descending select pairs; return result.ToList<Student>();
}
调用方法。
List<Student> stu = new List<Student>();
Student zs = new Student("张三",18,"福州",rnd.Next(300,500));
Student ls = new Student("李四",19,"北京",rnd.Next(300,500));
Student ww = new Student("王武",19,"黑龙江",rnd.Next(300,500));
stu.Add(zs);
stu.Add(ls);
stu.Add(ww); stu= SortList(stu);