GroupBy的匿名对象奇怪的结果

时间:2015-03-30 15:27:55

标签: c# linq dictionary

在这种情况下,我从GroupBy获得意外结果,我希望Dictionary<string,List<object>>来自GroupBy。但浏览器收到的内容如下:[{playdate, experiencetype...}, { ... }, { }], [{playdate, experiencetype,... }, { } ],...

所以即使对象 被分组到数组中也没有密钥,但我希望密钥在那里。我设置了一个断点并检查了packagedAjax,似乎有GroupedEnumerable包含Lookups。有什么想法吗?

var packagedAjax = showtimesByMovieAndLocation
                .Select(x =>
                        new
                        {
                            playdate = x.PlayDate,
                            experiencetype = x.FFCode,
                            vistasessionid = x.SessionID,
                            areacode = x.AreaCode
                        })
                .GroupBy(x => x.experiencetype);
return new JsonpResult(packagedAjax, Request.QueryString["callback"]);

1 个答案:

答案 0 :(得分:3)

GroupBy会返回IGrouping,而不是词典。如果您想要词典,请使用.ToDictionary()转换它:

var packagedAjax = showtimesByMovieAndLocation
            .Select(x =>
                    new
                    {
                        playdate = x.PlayDate,
                        experiencetype = x.FFCode,
                        vistasessionid = x.SessionID,
                        areacode = x.AreaCode
                    })
            .GroupBy(x => x.experiencetype)
            .ToDictionary(g => g.Key, g => g.ToList());