LINQ分组依据为字典对象 [英] LINQ Group By into a Dictionary Object

查看:83
本文介绍了LINQ分组依据为字典对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用LINQ从List<CustomObject>创建Dictionary<string, List<CustomObject>>.我可以使用"var"使它正常工作,但是我不想使用匿名类型.这就是我所拥有的

I am trying to use LINQ to create a Dictionary<string, List<CustomObject>> from a List<CustomObject>. I can get this to work using "var", but I don't want to use anonymous types. Here is what I have

var x = (from CustomObject o in ListOfCustomObjects
      group o by o.PropertyName into t
      select t.ToList());

我也尝试过使用x从LINQ库中使用Cast<>(),但是由于它是无效的强制转换,我遇到了编译问题.

I have also tried using Cast<>() from the LINQ library once I have x, but I get compile problems to the effect of it being an invalid cast.

推荐答案

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());

这篇关于LINQ分组依据为字典对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆