旗下导航:搜·么
当前位置:网站首页 > .Net教程 > 正文

C#.NET: List<Source>转Dictionary<Source.Key,List<Source>>【C#.Net教程】,C#.NET,Dictionary,Source

作者:搜教程发布时间:2019-11-27分类:.Net教程浏览:27评论:0


导读:C#.NET应用ToDictionary(),GroupBy(),能够将List转化为Dictionary,主须要一行代码!起首看一下需求,已知cars,即是:...

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

标签:C#.NETDictionarySource


欢迎 发表评论: