声明需要操作的Student类以及要转换的Person类
public class Student:IFormattable,IComparable<Student>
{
public int ID { get; set; }
public string Name { get; set; }
public double Score { get; set; }
public Student(int id,string name,double score)
{
this.ID = id;
this.Name = name;
this.Score = score;
}
public override string ToString()
{
return string.Format( "Name:{0} ",Name);
}
public string ToString(string format, IFormatProvider formatProvider)
{
if (format==null) format = "N";
switch (format.ToUpper())
{
case "N": //Name
return ToString();
case "NI": //Name ID
return string.Format("Name:{0},ID:{1}",Name,ID);
case "A": //Name ID Score
return string.Format("Name:{0},ID:{1},Sceor:{2}", Name, ID, Score);
default:
throw new FormatException(string.Format(formatProvider, "Format{0} is not suported", format));
}
}
//实现排序功能,需要实现此方法,默认用名排序
public int CompareTo(Student other)
{
int compare = this.Name.CompareTo(other.Name);
if (compare==0)
{
return this.Score.CompareTo(other.Score);
}
return compare;
}
}
public class Person
{
public int Id;
public string Name;
public Person(string name,int id)
{
this.Name = name;
this.Id = id;
}
}
基本操作命令
var XM = new Student(001,"小明",80);
var XG = new Student(002,"小刚",85);
var stus = new List<Student>() { XM, XG };
stus.Add(new Student(003,"小红",90));
//通过AddRange添加多个
stus.AddRange(new Student[] { new Student(004,"小芳",85),new Student(005,"小丽",82)});
//初始化时直接添加多个实例
//var stus = new List<Student>(new Student[] { new Student(004, "小芳", 85), new Student(005, "小丽", 82) });
//通过Insert添加
//stus.Insert(2,new Student(002,"小李",58));
//通过InsertRange在指定索引处添加
//stus.InsertRange(2,new Student[] { new Student(004, "小芳", 85), new Student(005, "小丽", 82) });
//通过所引起访问
Student stu1 = stus[2];
//统计列表的数量
//Console.WriteLine(stus.Count);
//通过For循环打印列表
//for (int i = 0; i < stus.Count; i++)
//{
// Console.WriteLine(stus[i]);
//}
//通过foreach打印
//foreach (Student stu in stus)
//{
// Console.WriteLine(stu);
//}
//通过ForEach打印
stus.ForEach(Console.WriteLine);
//可以通过更改A来控制显示的信息
stus.ForEach(r => Console.WriteLine("{0:A}",r));
//根据索引删除元素
//stus.RemoveAt(3);
//根据对象移除
//stus.Remove(stus[2]);
//stus.Remove(XG);
//int index1 = stus.IndexOf();
//通过对象某个属性查找匹配对象的索引
int index2 = stus.FindIndex(r => r.ID == 003);
//通过对象某个属性查找所有匹配对象中的第一个对象
var stu2 = stus.FindIndex(r => r.ID == 003);
//通过对象某个属性查找所有匹配对象中的最后一个对象
var stu3 = stus.FindLast(r => r.ID == 003);
//只有集合中的元素实现了Icomparable接口,才能使用不带参数的Sort()方法
//查找符合条件的实例集合
List<Student> stus1 = stus.FindAll(r=>r.Score>90);
//通过reverse()方法可以逆转序列
stus.Reverse();
//根据分数对列表排序
stus.Sort((s1,s2)=>s1.Score.CompareTo(s2.Score));
//将student列表转成erson列表,注意两个类之间属性的转换关系
List<Person> persons = stus.ConvertAll(s=>new Person(s.Name,s.ID));
persons.ForEach(s=>Console.WriteLine(s.Name+s.Id));