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})); }