如何使用LINQ获取Dictionary <string,List <Object>?

Fra*_*ega 1 c# linq dictionary

我有一个看起来像这样的对象:

class Model
{
   public string Category {get;set;}
   public string Description {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

目前我正在使用Linq获取这些对象的完整列表,然后手动设置字典,如下所示:

   List<Model> models = //get list from repository and then with linq order them by category and description

Dictionary<string, List<Model>> dict= new Dictionary<string, List<Model>>();

            foreach (var m in models)            {
                if (dict.ContainsKey(m.Category))
                {
                    dict[m.Category].Add(m);
                }
                else
                {
                    dict.Add(m.Category, new List<Model> { m });
                }    
            }
Run Code Online (Sandbox Code Playgroud)

这样我就可以使用键访问某个类别的所有模型.

有没有办法用LINQ查询直接生成字典?

谢谢!

And*_*ber 6

你见过这Lookup课吗?(msdn)

您可以通过调用Enumerable.ToLookup()方法(msdn)来创建它

它基本上就是你想要的,并处理欺骗键.


San*_*ken 5

是的,有一种方法,但要完成这项工作,你需要先将它们分组(避免重复键):

var dict = (from model in models
            group model by model.Category into g
            select g).ToDictionary(x => x.Key, x => x.ToList());
Run Code Online (Sandbox Code Playgroud)

(当你在它的时候,我想知道这个和.ContainsKey()方式的表现是什么)