List 类似于ArrayList ,是ArrayList的升级版,推荐是用List,不使用ArrayList 。
static void Main(string[] args) { List<string> liststr = new List<string>(); List<int> listint = new List<int>(); listint.Add(100); listint.Add(200); listint.Add(399); Dictionary<string, int> dickv = new Dictionary<string, int>(); dickv.Add("张三",100); dickv.Add("李四",99); Console.WriteLine(dickv["张三"]); Console.WriteLine(dickv["李四"]); foreach (KeyValuePair<string,int> item in dickv) { Console.WriteLine("{0},{1}",item.Key,item.Value); } Console.ReadKey(); }练习1 --奇偶数分拣,左边为偶,右边为奇
static void Main(string[] args) { string str = "1 32 5 74 9 11 13 42 54"; string [] number = str.Split(' '); List<string> lsint = new List<string>(); for (int i = 0; i < number.Length; i++) { if (int.Parse(number[i]) % 2 == 0) { lsint.Add(number[i]); } } for (int i = 0; i < number.Length; i++) { if (!(int.Parse(number[i]) % 2 == 0)) { lsint.Add(number[i]); } } for (int i = 0; i < lsint.Count; i++) { Console.Write(lsint[i]+" "); } Console.ReadKey(); }// 练习2 --把List集合转换为数组 int[] newarray = listodd.ToArray();
static void Main(string[] args) { int[] arrint = new int[5] {1,2,3,4,5 }; List<int> listodd = new List<int>(); for (int i = 0; i < arrint.Length; i++) { if (arrint[i] % 2 != 0) { listodd.Add(arrint[i]); } } int[] newarray = listodd.ToArray();--把List<T>集合转换为数组 for (int i = 0; i < newarray.Length; i++) { Console.WriteLine(newarray[i]); } Console.Read(); }练习3 从一个整数的List中找出最大、最小的数、排序等
static void Main(string[] args) { List<int> lsint = new List<int>() {1,2,3,4,5,6,7,8,9,11,21,31,14,51,16,71,18,82,49,59 }; int max= lsint.Max(); int min = lsint.Min(); lsint.Sort(); Console.WriteLine(max); Console.WriteLine(min); for (int i = 0; i < lsint.Count; i++) { Console.WriteLine(lsint[i]); } Console.Read(); }练习4 把123转换为一二三
static void Main(string[] args) { string str = "1一 2二 3三 4四 5五 6六 7七 8八 9九 0零"; Dictionary<char, char> dict = new Dictionary<char, char>(); string[] number = str.Split(' '); for (int i = 0; i < number.Length; i++) { dict.Add(number[i][0], number[i][1]); } string number2 = Console.ReadLine(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < number2.Length; i++) { sb.Append(dict[number2[i]]); } Console.WriteLine(sb); Console.Read(); }练习5 统计每种字母出现的次数 重点
static void Main(string[] args) { string str = "wjdslkjfdkslayfwqbfewqoiufhewquiofhiewuqfi!@%%56oewq"; Dictionary<char, int> dict = new Dictionary<char, int>(); for (int i = 0; i < str.Length; i++) { if (dict.ContainsKey(str[i])) { dict[str[i]]++; } else { dict[str[i]] = 1; } } foreach (KeyValuePair<char,int> keyvalue in dict) { Console.WriteLine("字母{0}出现了{1}次",keyvalue.Key,keyvalue.Value); } Console.Read(); }