复杂的LINQ查询

时间:2011-03-01 08:50:20

标签: c# linq

考虑集合

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}
        };

问题是:如何编写LINQ查询以对Age on Person进行分组,然后计算每个具有相同名称的组中的人数?

我尝试使用group by运算符,嵌套查询所有可能性仍然无法找出确切的查询。

此致 哎呀

4 个答案:

答案 0 :(得分:9)

怎么样

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
            };

Names属性的名称为Key,然后您可以为每个名称获取Count()

答案 1 :(得分:2)

基本相同:

var peeps = 
    people.GroupBy(p => p.Age).Select(gp => new
          {
              Aged = gp.Key,
              Count = gp.Count(),
              NameGrp = gp.GroupBy(pers => pers.Name)
          });

吉姆

答案 2 :(得分:0)

这与年龄和姓名的分组没有什么不同,包括计数和按年龄和名称的可选顺序。对对的LINQ操作通常可以通过简单地使用匿名类型来完成:

var people = new List<Person> { 
    new Person { FirstName = "John", LastName = "Leidegren", Age = 25 },
    new Person { FirstName = "John", LastName = "Doe", Age = 25 },
    new Person { FirstName = "Not john", LastName = "Doe", Age = 26 },
};

foreach (var g in (from p in people
                   group p by new { p.Age, p.FirstName }))
{
    Console.WriteLine("Count: {0}", g.Count());

    foreach (var person in g.OrderBy(x => x.FirstName))
    {
        Console.WriteLine("FirstName: {0}, LastName: {1}, Age: {2}"
            , person.FirstName
            , person.LastName
            , person.Age);
    }
}

非常清楚这里的唯一键是什么,可以在不改变剩余程序结构的情况下进行更改。

答案 3 :(得分:0)

List<Person> persons = 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}
};
var out1 = persons.GroupBy(p => new { p.Age, p.Name }).Select(s => new { Name = s.Key.Name,age = s.Key.Age, cnt = s.Count() }); ;
System.Threading.Tasks.Parallel.ForEach(out1, item => Console.WriteLine(item.Name + " " + item.age + " " + item.cnt));