Thufir Hawat
Thufir Hawat

Reputation: 476

GroupBy of Anonymous Object strange result

I am getting an unexpected result from GroupBy in this case, I expect a Dictionary<string,List<object>> from GroupBy. But the browser receives something like: [{playdate, experiencetype...}, { ... }, { }], [{playdate, experiencetype,... }, { } ],...

So there are no Keys even though the objects are grouped into arrays, but I want Keys to be there. I put up a breakpoint and checked packagedAjax, and there seems to be a GroupedEnumerable there containing Lookups. Any thoughts?

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"]);

Upvotes: 0

Views: 51

Answers (1)

David
David

Reputation: 10708

GroupBy returns an IGrouping, not a Dictionary. If you want a Dictionary, convert it using .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());

Upvotes: 3

Related Questions