按属性分组列出<person>并获取分组的次数</person>

时间:2013-02-20 08:17:40

标签: c# list properties linq-group

假设我有一个名为Person的课程:

public class Person
{
    public int Age { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

以及人员名单:

Person { Age = 20, FirstName = "John", LastName = "Joe" }
Person { Age = 20, FirstName = "John", LastName = "Joe" }
Person { Age = 10, FirstName = "James", LastName = "Dokes" }

我想要的是(新的或旧的具有新属性)列表,按年龄,名字和姓氏对人进行分组。我还想知道该对象被分组的次数。

所以上面的结果是:

Person { Age = 20, FirstName = "John", LastName = "Joe", Count = 2 }
Person { Age = 10, FirstName = "James", LastName = "Dokes", Count = 1 }

3 个答案:

答案 0 :(得分:6)

简单:

people.GroupBy(x => new { x.Age, x.FirstName, x.LastName })
      .Select(x => new { x.Key.Age, x.Key.FirstName, x.Key.LastName, Count = x.Count() });

答案 1 :(得分:1)

就在我发布之前,我已经从JustAnotherUserYouMayKnow看到了答案,所以本来要取消,但是我发布的只是为了仅使用GroupBy显示相同的结果,使用resultSelector参数(而不是单独的投影)

var personList = new List<Person> {
    new Person { Age = 20, FirstName = "John", LastName = "Joe" },
    new Person { Age = 20, FirstName = "John", LastName = "Joe" },
    new Person { Age = 10, FirstName = "James", LastName = "Dokes"}};

var results = personList.GroupBy(per => new { per.Age, per.FirstName, per.LastName },
    (key, items) => new { key.Age, key.FirstName, key.LastName, Count = items.Count() } );

答案 2 :(得分:1)

非流程替代方案:

List<Person> ls = new List<Person>();
ls.Add (new Person() { Age = 20, FirstName = "John", LastName = "Joe" });
ls.Add(new Person() { Age = 20, FirstName = "John", LastName = "Joe" });
ls.Add(new Person() { Age = 10, FirstName = "James", LastName = "Dokes" });

var result = (from cur in ls
                group cur by new { Age = cur.Age, Name = cur.FirstName, LastName = cur.LastName }
                into tmpResult
                select new { tmpResult.Key.Age,tmpResult.Key.LastName,tmpResult.Key.Name,Count = tmpResult.Count()});