0

I have an item object that looks like this:

item["siteId"] = "{7BAD6B24-3B69-4CB9-AD02-9B0003C1927D}";
item["webId"] = "{F66ED194-A91C-49FA-8672-F87DFEE3EF08}";
item["value"] = "blah";

This example represents that a value blah is in web {F66ED194-A91C-49FA-8672-F87DFEE3EF08} which is in site {7BAD6B24-3B69-4CB9-AD02-9B0003C1927D}.

This item is in a collection with many others. The collection is called items.

I've tried to write a LINQ query that groups first by site ID and then by web ID, but can't get the syntax correct. Here's my attempt:

var itemGroups = from item in items.Cast<SPListItem>()
     let siteId = (string) item["siteId"]
     group item by siteId
     into siteGroup
     select new
        {
            SiteId = siteId,
            SiteGroups =
                from siteItem in siteGroup
                let webId = (string) siteItem["webId"]
                group siteItem by webId into webGroup
                select new
                    {
                        WebId = webId,
                        WebGroups = from siteItem in webGroup
                    }
                };

The let clauses don't seem to work within the anonymous type, and I'm not sure what to add to the last from clause.

Can anyone please assist?

Alex Angas
  • 59,219
  • 41
  • 137
  • 210

1 Answers1

2

You can't use variables, that you declared before group by. In your case, solution is simple. Also, you can't abruptly end your inner query like that. And I would structure the query little different.

var itemGroups = from item in items.Cast<SPListItem>()
                    let siteId = (string) item["siteId"]
                    group item by siteId
                    into siteGroup
                    let siteGroups = from siteItem in siteGroup
                                    let webId = (string) siteItem["webId"]
                                    group siteItem by webId
                                    into webGroup
                                    select new
                                                {
                                                    WebId = webGroup.Key,
                                                    WebGroups = (from wg in webGroup select wg).ToList()
                                                }
                    select new
                            {
                                SiteId = siteGroup.Key,
                                SiteGroups = siteGroups.ToList()
                            };
Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • can you help me with this linq query please:http://stackoverflow.com/questions/38120664/how-to-group-by-on-2-child-entities-and-get-total-of-both-this-child-entities – I Love Stackoverflow Jun 30 '16 at 12:41