C#高级语法基础知识总结6——字符串&集合

字符串

 

集合

列表声明

Var intList=new List<int>();

Var racers=new List<Racer>();

List<int> intList=new List<int>(10);//大小为10,倍数增加

 

使用Capacity属性可以获取和设置集合的容量

使用Count属性可以获取集合的元素个数

Add()方法添加元素

AddRange()可以一次给集合添加多个元素。

Insert()方法可在指定位置插入元素

RemoveAt(index),Remove(),RemoveRange(index,count)删除元素

搜索IndexOf(),LastIndexOf(),FindIndex(),FindLastIndex(),Find()和FindLast()。

如果只检查元素是否存在,List<T>类就提供了Exists()方法。

排序:List<T>类可以使用sort()方法对元素排序。

 

类型转换

使用List<T>类的ConverAll<TOutput>()可以把所有类型的集合转换为另一种类型。

类型转换
 1  
 2             Console.WriteLine("集合-----------");
 3 
 4             Console.WriteLine("列表");
 5 
 6             List<int> intList = new List<int>(10);
 7 
 8             List<string> strList = new List<string>() { "苏国强", "盖茨" };//初始化
 9 
10             Console.WriteLine("Capacity属性获取集合的容量{0}" , intList.Capacity);
11 
12             Console.WriteLine("Count属性获取集合元素个数{0}", intList.Count);
13 
14             Console.WriteLine("Add()方法添加元素");
15 
16             intList.Add(1);
17 
18             intList.Add(2);
19 
20             Console.Write("添加元素后列表");
21 
22             foreach (var a in intList)
23 
24             {
25 
26                 Console.Write(a+",");
27 
28             }
29 
30             Console.WriteLine();
31 
32             Console.WriteLine();
33  
34 
35             Console.WriteLine("AddRange()方法添加元素");
36 
37             intList.AddRange(new int[] { 3, 4 });
38 
39             Console.Write("添加元素后列表");
40 
41             foreach (var a in intList)
42 
43             {
44 
45                 Console.Write(a+",");
46 
47             }
48 
49             Console.WriteLine();
50 
51             Console.WriteLine();
52  
53 
54             Console.WriteLine("Insert()方法插入元素");
55 
56             strList.Insert(1, "乔布斯");
57 
58             Console.Write("插入元素后列表");
59 
60             foreach (var a in strList)
61 
62             {
63 
64                 Console.Write(a + ",");
65 
66             }
67 
68             Console.WriteLine();
69 
70             Console.WriteLine();
71  
72 
73             Console.WriteLine("RemoveAt()方法删除元素");
74 
75             strList.RemoveAt(1);
76 
77             Console.Write("删除元素后列表");
78 
79             foreach (var a in strList)
80 
81             {
82 
83                 Console.Write(a + ",");
84 
85             }
86 
87             Console.WriteLine();
88 
89             Console.WriteLine();
90 
91             Console.WriteLine("使用IndexOf()查询返回索引或-1");
92 
93             int index1 = strList.IndexOf("苏国强");
94 
95             Console.WriteLine(index1);

 

 

posted @ 2012-07-16 22:48  Ghost Soar  阅读(660)  评论(0编辑  收藏  举报