C#.NET 利用ToDictionary(),GroupBy(),可以將List轉化為Dictionary,主需要一行代碼!
首先看一下需求,已知cars,等於:
List<Car> cars = new List<Car>(){ new Car(1,"audiA6","private"), new Car(2,"futon","merchant"), new Car(3,"feiren","bike"), new Car(4,"bukon","private"), new Car(5,"baoma","private"), new Car(6,"dayun","merchant") };
1)我想以id為鍵,值為Car轉化為一個字典idCarDict,方法如下:
var idCarDict = cars.ToDictionary(car=>car.id);
這樣保證能正確轉化的前提為,id在列表中沒有重複值。如果有重複的,會拋出向字典中添加重複值的異常。
2)我想以type為鍵,值car的List的typeDict,方法如下:
Dictionary<string, List<Car>> typeCarDict = cars.GroupBy(car => car.type).ToDictionary(r => r.Key, r => r.ToList());
分步解釋:
第一步分組
cars.GroupBy(car=>car.type) //返回的結果類型為: //IEnumerable<IGroup<string,car>>;//其中string等於car.type,也就是分組的鍵
第二步將IEnumerable類型轉化為字典,選取合適的鍵,
ToDictionary(r=>r.Key,r=>r.ToList());//r參數代表分組對象,r.Key便是car.type;//r.ToList()操作後將分組對象轉化為List對象
這種轉化代碼簡介,比以下foreach遍曆得到以car.type的字典簡潔許多:
var dict = new Dictionary<string,List<Car>>();foreach(var car in cars){ if(dict.Contains(car.type)) dict[car.type].Add(car); else dict.Add(car.type,new List<Car>(){car}));}
C#.NET 利用ToDictionary(),GroupBy(),可以將List轉化為Dictionary,主需要一行代碼!
首先看一下需求,已知cars,等於:
List<Car> cars = new List<Car>(){ new Car(1,"audiA6","private"), new Car(2,"futon","merchant"), new Car(3,"feiren","bike"), new Car(4,"bukon","private"), new Car(5,"baoma","private"), new Car(6,"dayun","merchant") };
1)我想以id為鍵,值為Car轉化為一個字典idCarDict,方法如下:
var idCarDict = cars.ToDictionary(car=>car.id);
這樣保證能正確轉化的前提為,id在列表中沒有重複值。如果有重複的,會拋出向字典中添加重複值的異常。
2)我想以type為鍵,值car的List的typeDict,方法如下:
Dictionary<string, List<Car>> typeCarDict = cars.GroupBy(car => car.type).ToDictionary(r => r.Key, r => r.ToList());
分步解釋:
第一步分組
cars.GroupBy(car=>car.type) //返回的結果類型為: //IEnumerable<IGroup<string,car>>;//其中string等於car.type,也就是分組的鍵
第二步將IEnumerable類型轉化為字典,選取合適的鍵,
ToDictionary(r=>r.Key,r=>r.ToList());//r參數代表分組對象,r.Key便是car.type;//r.ToList()操作後將分組對象轉化為List對象
這種轉化代碼簡介,比以下foreach遍曆得到以car.type的字典簡潔許多:
var dict = new Dictionary<string,List<Car>>();foreach(var car in cars){ if(dict.Contains(car.type)) dict[car.type].Add(car); else dict.Add(car.type,new List<Car>(){car}));}