集合本质上是一个类,最起码实现IEnumerable<T>或非泛型类型 IEnumerable
其他集合接口有:
IList<T>:按照特定顺序存储值并按位置访问它们。
IDictionary<TKey,TValue>:键及其关联的值的无序列表。
ICollection<T>:Count属性返回元素计数,CopyTo()方法允许将集合转换成数组。
C#中的集合包括:Stack、Queue、List、Hashtable、Dictionary等。
在List<T>中查找特定元素可以使用Contains() (返回bool值),IndexOf()(返回第一个索引),LastIndexOf()(返回最后一个索引),还可以使用 BinarySearch()
BinarySearch() 采用二叉搜索算法,但要求元素已排好序。如果事先没有排好序,即使元素存在也可能找不到。BinarySearch()一个有用的功能是,假如没有找到指定的元素,会返回一个负整数。该值的按位取反(~)结果是“大于被查找元素的下一个元素”的索引,如果没有更大的值,就返回(~元素总数)
List<string> list = new List<string>() { "private","protect","public"};
list.Sort();
int search = list.BinarySearch("protect internal");
if(search<0)
{
list.Insert(~search, "protect internal");
}
foreach (var item in list)
{
Console.Write(item+", ");
}
private, protect, protect internal, public,
1、集合初始化器
在集合实例化期间用一组初始成员构造该集合
List<string> list = new List<string>() { "a", "b", "c" };
或:
List<string> list = new List<string> { "a", "b", "c" };
字典的初始化语法稍复杂点:
//C# 6.0 or later
Dictionary<string, ConsoleColor> colorMap1 = new Dictionary<string, ConsoleColor>
{
["a"]=ConsoleColor.Green,
["b"]=ConsoleColor.Blue,
["c"]=ConsoleColor.Red,
};
//before C#6.0
Dictionary<string, ConsoleColor> colorMap2 = new Dictionary<string, ConsoleColor>
{
{"a",ConsoleColor.Red},
{"b",ConsoleColor.Green},
{"c",ConsoleColor.Blue},
};
2、foreach
foreach使用迭代器模式遍历集合,不依赖索引,不需要事先知道集合中有多少元素
编译器禁止对foreach变量赋值。在foreach执行期间,集合中的元素计数不能变,集合项本身也不能更改
3、标准查询操作符
(1)Where:筛选
输出是一个新的 IEnumerable<T>集合
List<string> list1 = new List<string> { "aa","abc","bc"};
List<string> list2 = list1.Where(item => item.StartsWith("a")).ToList();
list2.ForEach(item => Console.WriteLine(item));
aa
abc
(2)Select:投射
可以对集合中的每个数据项进行类型转换
//投射成FileInfo
IEnumerable<string> fileList = Directory.GetFiles("D:");
IEnumerable<FileInfo> f