Title: Grouping and counting occurences of a parameter within each group
Tags: linq;sqlite;group-by;linqpad
Question: I'm fiddling with LINQPad and I'm sure this question has been asked but I've been struggling and searching for quite a while.

I have a collection like this:

```Age  Material
---  --------
3    Steel
3    Steel
3    PVC
4    Steel
4    PVC
```

I want to group it first by Material, and then count the occurences of each Age within each Material group, resulting in something like this:

```{Mat = Steel,
   [(Age = 3, Count = 2),
    (Age = 4, Count = 1)]}
{Mat = PVC,
   [(Age = 3, Count = 1),
    (Age = 4, Count = 1)]}
```

I know this has to do with nested groups but I can't get it right. I've been trying stuff like this (only without the question marks), but I don't know how to get to the items in each group:

```var matGroups = from line in Pipelines                              
                group line by line.Material into matGroup
                from ???? in ???
                group ???? by ???.Age;
```

If its relevant, the data store I'm querying is in SQLite.

UPDATE

The following code gets me the data I want. However, I would still like to know the proper way to do this in a single query, if possible.

```var materials = from p in Pipelines
                group p by p.Material into matGroup
                select matGroup.Key;

foreach (string material in materials)
{
    var ages = from p in Pipelines
               where p.Material == material
               group p by p.Age into ageGroup
               select new {Age = ageGroup.Key, Count = ageGroup.Count()};

    ages.Dump(material + " Pipelines");
}
```

Comment: I have never used LINQ, but the SQL command you want is simple: `select material, age, count(*) from pipelines group by material, age;` Maybe that will help...

Here is the accepted answer: It is just a grouping by ```Age``` and ```Material```:

```from p in Pipelines
group p by new { p.Material, p.Age } into g
orderby g.Key.Material, g.Key.Age
select new { g.Key.Material, g.Key.Age, Count = g.Count () }
```



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:05/09/12', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<linq><sqlite><group-by><linqpad>', 'Title': 'Grouping and counting occurences of a parameter within each group', 'ViewCount': 293, 'id': 10518980, 'user_AboutMe': '<p>Software development engineer.</p>\n', 'user_AccountId': 291492.0, 'user_DisplayName': 'Pieter Müller', 'user_Reputation': 4463.0, 'user_Views': 340.0, 'user_id': 593677.0}}