110,499
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
SortedList<int, string> sortedList = new SortedList<int, string>();
sortedList.Add(3, "张三");
sortedList.Add(1, "李四");
sortedList.Add(2, "王五");
foreach (var item in sortedList)
{
Console.WriteLine(string.Format("{0}号同学是:{1}", item.Key, item.Value));
}
Console.ReadKey();
}
}
}
//输出结果:
//1号同学是:李四
//2号同学是:王五
//3号同学是:张三
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
Student s1 = new Student(24, "A");
Student s2 = new Student(17, "B");
Student s3 = new Student(18, "C");
Student s4 = new Student(18, "B");
SortedList<Student, int> s = new SortedList<Student, int>();
s.Add(s1, 60);
s.Add(s2, 55);
s.Add(s3, 50);
s.Add(s4, 70);
Console.WriteLine("先按学生年龄升序排列,如果年龄相同,则按姓名升序排列。");
foreach (var item in s)
{
Console.WriteLine(string.Format("{0}岁姓名为{1}的同学体重为:{2}公斤", item.Key.Age, item.Key.Name, item.Value));
}
Console.ReadKey();
}
}
public class Student : IComparable<Student>
{
private int m_Age;
private string m_Name;
public int Age
{
get { return m_Age; }
set { m_Age = value; }
}
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
public Student(int i_Age, string i_Name)
{
this.m_Age = i_Age;
this.m_Name = i_Name;
}
/// <summary>
/// 先按学号升序排列,再按名字升序排列
/// </summary>
/// <param name="other">比较对象</param>
/// <returns>比较结果</returns>
public int CompareTo(Student other)
{
int result = this.m_Age.CompareTo(other.m_Age);
if (result == 0)
{
result = this.m_Name.CompareTo(other.m_Name);
}
return result;
}
}
}
//输出结果:
//先按学生年龄升序排列,如果年龄相同,则按姓名升序排列。
//17岁姓名为B的同学体重为:55公斤
//18岁姓名为B的同学体重为:70公斤
//18岁姓名为C的同学体重为:50公斤
//24岁姓名为A的同学体重为:60公斤