前言:這篇部落格我主要說一下C#中泛型的使用,也就是List和Dictionary字典集合的使用,我在這裡說的主要說的是如何去使用,而不是長篇大論的去研究泛型的底層,但我們有一定程式的時候在研究,使學習的能夠很快的學習集合然後自己研究集合的一些進階用法,不在最後還列舉出了一些常用的小案例。
- 泛型集合
(1) 泛型集合就是不確定的集合,文法中有一個角括弧,裡面放什麼類型,這個集合就變成什麼類型
(2)List
1)舉例說明:
static void Main(string[] args){ List<int> listInt = new List<int>(); listInt.AddRange(new int[] { 1, 34, 54, 65, 76, 78 }); int sum = 0; for (int i = 0; i < listInt.Count; i++) { sum += listInt[i]; } Console.WriteLine(sum); Console.ReadKey();}
(3)Dictionary (Dictionary<TKey,TValue>)
定義一個泛型集合:Dictionary<TKey,Tvalue> dic=new Dictionary<TKey,Tvalue>();
1)增加
Add 將指定的索引值對添加到字典集合中
方法原型:void dic.Add(T key,T Value)
Dictionary<string, string> openWith =new Dictionary<string, string>(); try{ openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); openWith.Add("txt", "winword.exe");}catch (ArgumentException){ Console.WriteLine("添加失敗,請檢查");}
//輸出結果是添加失敗,請檢查,以為添加了相同的鍵
2)刪除
Remove 從字典集合中移除指定的鍵的值
方法原型:bool dic.Remove(TKey key);
Dictionary<string, string> openWith =new Dictionary<string, string>();openWith.Add("txt", "notepad.exe");openWith.Add("bmp", "paint.exe");openWith.Add("dib", "paint.exe");openWith.Add("rtf", "wordpad.exe");openWith.Remove("txt"); foreach (var item in openWith){ Console.WriteLine(item.Key);}//輸出結果:bmp dib rtfClear 從字典集合中移除所有的值 方法原型: void dic.Clear(); Dictionary<string, string> openWith =new Dictionary<string, string>(); openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); openWith.Clear(); foreach (var item in openWith) { Console.WriteLine(item.Key); } //輸出結果為空白
3)查詢
ContainsKey 得到字典集合中是否包含指定的鍵
方法原型:bool dic.ContainsKey(TKey,key);
Dictionary<string, string> openWith = new Dictionary<string, string>();openWith.Add("txt", "notepad.exe");openWith.Add("bmp", "paint.exe");openWith.Add("dib", "paint.exe");openWith.Add("rtf", "wordpad.exe");if (!openWith.ContainsKey("txt")){ openWith.Add("txt", "notepat++");}else{ Console.WriteLine("已經存在");}
//輸出結果:已經存在
COntainsValue 得到字典集合中是否包含指定的值
方法原型:bool dic.ContainsValue(TValue,value);
Dictionary<string, string> openWith = new Dictionary<string, string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
if (openWith.ContainsValue("paint.exe"))
{
Console.WriteLine("已經存在");
}
//輸出結果:已經存在
4)TryGetValue 獲得於指定的鍵相關聯的值
方法原型:bool dic.TryGetValue(TKey key,out TVlaue value);
Dictionary<string, string> openWith = new Dictionary<string, string>();openWith.Add("txt", "notepad.exe");openWith.Add("bmp", "paint.exe");openWith.Add("dib", "paint.exe");openWith.Add("rtf", "wordpad.exe");string value = "";if (openWith.TryGetValue("rtf", out value)){ Console.WriteLine("Key=rtf,value={0}", value);}else{ Console.WriteLine("根據rtf鍵沒有找到對應的值");}
//輸出結果:key=rtf,value=wordpad.exe
1)舉例說明:
static void Main(string[] args)
{
Dictionary<char, string> dic = new Dictionary<char, string>();
dic.Add('1', "愛情這東西");
foreach (KeyValuePair<char, string> item in dic)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
(4)案例1:把分揀奇數的程式用泛型實現
static void Main(string[] args) { string str = "3 45 65 34 68 67 87 98"; //1 split string[] nums = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //2 list<string> List<string> odd = new List<string>();//奇數 List<string> even = new List<string>(); //偶數 //3 for迴圈判斷奇偶 for (int i = 0; i < nums.Length; i++) { //第一種方法 //int num = Convert.ToInt32(nums[i]); //if (num % 2 == 0) //{ // even.Add(nums[i]); //} //else //{ // odd.Add(nums[i]); //} //第二種方法 string num = nums[i]; char ch = num[num.Length - 1]; int last = ch - '0'; if ((nums[i][nums[i].Length - 1] - '0') % 2 == 0) { even.Add(nums[i]); } else { odd.Add(nums[i]); } } odd.AddRange(even); //4轉換 Console.WriteLine(string.Join(" ", odd.ToArray())); }
(5)案例2:將int數組中的奇數放到一個新的int數組中返回
static void Main(string[] args) { int[] nums = { 1, 3, 5, 565, 76, 78, 98, 90, 4, 545 }; List<int> listInt = new List<int>(); for (int i = 0; i < nums.Length; i++) { if (nums[i] % 2 == 1) { listInt.Add(nums[i]); } } for (int i = 0; i < listInt.Count; i++) { Console.WriteLine(listInt[i] + " "); } Console.ReadKey(); }
(6)案例3:從一個整數的List<int>中取出最大數
static void Main(string[] args) { int[] nums = { 2, 34, 454, 65, 76, 77, 778, 898, 989 }; int max = int.MinValue; int min = int.MaxValue; List<int> listInt = new List<int>(); listInt.AddRange(nums); for (int i = 0; i < listInt.Count; i++) { if (min > listInt[i]) { min = listInt[i]; } if (max < listInt[i]) { max = listInt[i]; } } Console.WriteLine(max); Console.WriteLine(min); }
(7)把123轉換為"壹貳三"
static void Main(string[] args) { string var = "壹貳三肆伍陸柒捌玖"; Dictionary<char, char> dic = new Dictionary<char, char>(); for (int i = 0; i <var.Length ; i++) { dic.Add((char)(i + '0'), var[i]); } while (true) { Console.Write("請輸入一行數字:"); string str = Console.ReadLine(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { char num = str[i]; char word = dic[num]; sb.Append(word); } Console.WriteLine(sb.ToString()); Console.ReadKey(); } }
(8)計算字串中每種字元出現的次數
static void Main(string[] args) { Dictionary<char, int> dic = new Dictionary<char, int>(); Console.Write("請輸入一句話"); string str = Console.ReadLine(); for (int i = 0; i < str.Length; i++) { //dic.Add(str[i], 1); //dic[str[i]]++; char current = str[i]; if (dic.ContainsKey(current)) { //如果集合不存在這個資料 //dic[current] += 1; dic[current]++; } else { //如果集合中不存在這個資料 dic.Add(current, 1); } } foreach (KeyValuePair<char, int> item in dic) { Console.WriteLine("子符{0}出現了{1}次", item.Key, item.Value); } Console.ReadKey(); }
- Dictionary就是Hashtable的泛型形式
(1) 哈爾演算法是一個函數
Add(Key,Value);
dic[Key];
(2)雜湊演算法是一個通過Key來計算地址的函數
1)傳入一個key和一個value後
2)通過雜湊演算法計算key的到一個地址
3)將地址存入索引值對集合,並將value存入地址所在的地方
4)等到訪問的時候直接通過key計算出地址,直接找到儲存的變數
- 能不能用for迴圈遍曆一個集合Dic
(1) 在for迴圈中如果不使用對應的遞增序號,"我"就認為不叫使用了for迴圈
(2)foreach迴圈的過程
1)找到資料來源,調用GetEnumertor方法,得到枚舉值
2)in,調用MoveNext方法
3)如果MoveNext返回true,使用Current得到當前資料
4)如果返回false,則跳出迴圈
static void Main(string[] args)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("1111", "2222");
dic.Add("0000", "3333");
var enumrator = dic.GetEnumerator();
//while (enumrator.MoveNext())
//{
// Console.WriteLine(enumrator.Current.Key + "," + enumrator.Current.Value);
//}
for (; enumrator.MoveNext(); )
{
Console.WriteLine(enumrator.Current.Key + "," + enumrator.Current.Value);
}
}
- 等於
(1) Equals 確定指定的Object是否等於當前的Object類型
方法原型:
bool Equals(Object obj)
Object Obj1 = new Object();
Object Obj2 = new Object();
Console.WriteLine(Obj1.Equals(Obj2));
Obj2 = Obj1;
Console.WriteLine(Obj1.Equals(Obj2));
輸出結果: False,True