Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complex LINQ query

Tags:

c#

linq

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

like image 607
Jeevan Avatar asked Mar 01 '11 08:03

Jeevan


2 Answers

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.

like image 182
driis Avatar answered Oct 15 '22 05:10

driis


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

like image 2
jim tollan Avatar answered Oct 15 '22 03:10

jim tollan