C# ToLookUp 詳解,ToLookUp 和ToDictionary的區別
阿新 • • 發佈:2018-12-12
ToDictionary 和ToLookUp 對 物件集合的操作帶來極大的方便,特別是對索引的提供。方便通過 key 來找到相應的鍵值,ToDictionary 轉換成是鍵值對 關係是一 一 對應的關係 且key 值是唯一的不能重複。微軟彷彿意識到ToDictionary 的不足,於是ToLookUp誕生了, ToLookUp 是ToDictionary 的擴充套件版本,個人理解: ToLookUp類似於Dictionary<string,List<string>>,好了廢話不說直接程式碼!
- private static void LookUpAndDic()
- {
- //建立學生列表
- List<Student> data = getStudents();
- //各個班級學生的分組
- ILookup<string, string> dic = data.ToLookup(item => item.classNo,item=> { return item.stuNo + " 姓名" + item.name; });
- foreach(var item in dic)
- {
- Console.WriteLine("年級編號:"+item.Key);
- foreach(var item1 in item)
- {
- Console.WriteLine("\t\t"+item1);
- }
- }
- Console.WriteLine();
- //獲取指定班級的學生
- IEnumerable<string> datas = dic["01"];
- foreach(string item in datas)
- {
- Console.WriteLine("一班的同學:"+item);
- }
- Console.WriteLine();
- //獲取班級個數
- int count = dic.Count;
- Console.WriteLine("獲取班級的個數:"+count);
- Console.WriteLine();
- //判斷某個班級是否存在
- if (dic.Contains("06"))
- {
- Console.WriteLine("06 班已存在!");
- }
- Console.ReadKey();
- }
- public class Student
- {
- /// <summary>
- /// 學生姓名
- /// </summary>
- public string name { get; set; }
- /// <summary>
- /// 年級代號
- /// </summary>
- public string classNo { get; set; }
- /// <summary>
- /// 學生Id
- /// </summary>
- public string stuNo { get; set; }
- }
- }
- /// <summary>
- /// 獲取所有的students
- /// </summary>
- /// <returns></returns>
- public static List<Student> getStudents()
- {
- return new List<Student>(){
- new Student() { stuNo="0101", classNo="06", name="liu" },
- new Student() { stuNo="0102", classNo="01", name="wang" },
- new Student() { stuNo="0103", classNo="01", name="li" },
- new Student() { stuNo="0104", classNo="02", name="wei" },
- new Student() { stuNo="0105", classNo="02", name="zhao" },
- new Student() { stuNo="0106", classNo="02", name="ma" },
- new Student() { stuNo="0107", classNo="04", name="a" },
- new Student() { stuNo="0108", classNo="03", name="shangGuan" },
- new Student() { stuNo="0109", classNo="03", name="zhang" },
- new Student() { stuNo="0110", classNo="03", name="jiang" },
- new Student() { stuNo="0111", classNo="03", name="wu" },
- new Student() { stuNo="0112", classNo="03", name="test" },
- new Student() { stuNo="0113", classNo="05", name="liu2" },
- };
- }