集合接口和类型
- 大多数接口都可在System.Collections和System.Collections.Generic名称空间中找到。泛型集合类位于System.Collections.Generic名称空间中;
接口及说明
列表
例子:将Racer类中的成员用作要添加到集合中的元素,以表示一级方程式的一位赛车手。这个类有5个属性:Id、Firstname、Lastname、Country和Wins的次数。在该类的构造函数中,可以传递赛车手的姓名和获胜次数,以设置成员。重写ToString()是为了返回赛车手的姓名。Racer类也实现了泛型接口IComparable,为Racer类中的元素排序,还实现了IFormattable接口
public class Racer:IComparable<Racer>,IFormattable
{
public int Id{get;}
public string FirstName{get;set;}
public string LastName{get;set;}
public string Country{get;set;}
public int Wins{get;set;}
public Racer(int id,string firstName,string lastName,string country):this(id,firstName,lastName,country,wens:0)
{}
public Racer(int id,string firstName,string lastName,string country,int wins)
{
Id=id;
FirstName=firstName;
LastName=lastName;
Country=country;
Wins=wins;
}
public override string ToString()=>$"{FirstName}{LastName}";
public string ToString(string format,IFormatProvider formatProvider)
{
if(format==null)format="N";
switch {format.ToUpper()}
{
case "N":
return ToString();
case "F":
return FirstName;
case "L"
return LastName;
case "W"
return $"{ToString()},Wins:{Wins}";
case "C":
return $"{ToString()},Country:{Country}",
case "A"
return $"{ToString()},Country:{Country} Wins:{Wins}";
default:
throw new FormatException(String.Format(formatProvider,$"Format(format)is not supported"));
}
}
public string ToString(string format)=>ToString(format,null);
public int CompareTo(Racer other)
{
int compare=LastName?.CompareTo(other?.LastName)??-1;
if(compare==0)
{
return FirstName?.CompareTo(other?.FirstName)??-1;
}
return compare;
}
}
创建列表
- 集合初始值设定项
var intList=new List<int>(){1,2}; var stringList=new List<string>(){"one","two"};
- 添加元素
- 使用Add()方法可以给列表添加元素 ``` var intList=new List(); intList.Add(1); intList.Add(2);
var stringList=new List(); stringList.Add(“one”); stringList.Add(“two”);
- 插入元素
racers.Insert(3,new Racer(6,“Phil”,“Hill”,“USA”,3)); 方法InsertRange()提供了插入大量元素的功能,类似于前面的AddRanger()方法。 ```
for (int i=0;i<racers.Count;i++>)
{
WriteLine(racers[i]);
}
foreach(var r in racers)
{
WriteLine(r);
}