List<T>
可以将集合看作为“长度可变的,具有很多方法的数组”
T为集合中元素的类型
增
1.void List<T>.Add(T item)
添加元素
List<string> list = new List<string>();
list.Add("abc");
2.void List<T>.AddRange(IEnumerable collection)
添加指定集合的元素。add方法添加数组的话只是添加一项(把数组看作一个整体),addrange方法添加的话,数组里有多少个元素就会添加多少项。
List<string> list = new List<string>();
string[] input = { "aa", "bb", "cc" };
list.AddRange(input);
删
1.bool List<T>.Remove(string item)
移除特定元素的第一个匹配的元素
如果成功移除 item,则为 true;否则为 false。 如果在 List 中没有找到item,该方法也会返回 false。
List<string> list = new List<string>();
string[] input = { "a", "b", "c" };
list.AddRange(input);
list.Remove("a");//执行完后,list只剩两项,b和c
2.void List<T>.RemoveAt(int index)
移除指定索引处的元素
List<string> list = new List<string>();
string[] input = { "a", "b", "c" };
list.AddRange(input);
list.RemoveAt(0);//执行完后,索引为0的a被移除
改
1.通过索引来改
List<string> list = new List<string>();
string[] input = { "a", "b", "c" };
list.AddRange(input);
list[2] = "d";//索引为2的c改成了d
查
1.bool List<T>.Contains(T item)
判断元素是否在集合中,找到则为true
List<string> list = new List<string>();
string[] input = { "a", "b", "c" };
list.AddRange(input);
list.Contains("b");
if (list.Contains("b"))
{
Console.WriteLine("存在b");
}
else
{
Console.WriteLine("不存在b");
}
2.intl List<T>.IndexOf(T item)
返回指定元素的索引
List<string> list = new List<string>();
string[] input = { "a", "b", "c" };
list.AddRange(input);
int index=list.IndexOf("a");
Console.WriteLine(index);
//0
3.用for或foreach遍历
//用for
List<string> list = new List<string>();
string[] input = { "a", "b", "c" };
list.AddRange(input);
for (int i = 0; i < list.Count; i++)
{
Console.Write(list[i]);
}
//abc
foreach(集合中单个的类型 局部变量名 in 集合对象)
{
// 循环体
// 循环体当中“局部变量”表示集合中遍历的数据
}
foreach (string item in list)
{
Console.Write(item);
}
Dictionary<TKey,TValue>
添加数据,都是“键值对”的形式,方便快速查找,通过一个键取一个值,是一种无序的结构,键就是为了找数据用的,必须提供,不允许重复
增
1.void Dictionary<T,T>.Add(T key,T value)
添加键值对
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("generic", "泛型");
删
1.bool Dictionary<T,T>.Remove(T key)
移除指定键的值
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("generic", "泛型");
dic.Add("item", "项");
dic.Add("index", "索引");
dic.Remove("generic");
改
1.通过键值改
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("generic", "泛型");
dic["generic"]="泛型,通用的";
查
1.bool Dictionary<T,T>.ContainsKey(T key)
判断是否包含指定的键
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("generic", "泛型");
dic.Add("item", "项");
dic.Add("index", "索引");
if (dic.ContainsKey("item"))
{
Console.WriteLine("包含item");
}
else
{
Console.WriteLine("不包含item");
}
2.用foreach遍历
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("generic", "泛型");
dic.Add("item", "项");
dic.Add("index", "索引");
foreach (string item in dic.Keys)
{
Console.WriteLine("key为{0},value为{1}",item,dic[item]);
}