Consider the collection
List<Person> people = new List<Person>
{
new Person{Name = "A", SSN="1", Age = 23},
new Person{Name = "A", SSN="2", Age = 23},
new Person{Name = "B", SSN="3", Age = 24},
new Person{Name = "C", SSN="4", Age = 24},
new Person{Name = "D", SSN="5", Age = 23}
};
The question is: How can I write a LINQ query to group Person on Age and then count number of person with in each group having the same name?
I tried using group by operator, nested queries all possibilities still could not figure out the exact query.
Regards, Jeez
How about
var ages = from p in people
group p by p.Age into g
select new {
Age = g.Key,
Count = g.Count(),
Names = from prs in g
group prs by prs.Name
};
The Names property will have the name as the Key and you can then get Count()
for each name.
basically the same as:
var peeps =
people.GroupBy(p => p.Age).Select(gp => new
{
Aged = gp.Key,
Count = gp.Count(),
NameGrp = gp.GroupBy(pers => pers.Name)
});
jim
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With