0

假设我有一个名为 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 }
4

3 回答 3

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() });
于 2013-02-20T08:23:37.553 回答
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() } );
于 2013-02-20T08:31:28.857 回答
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()});
于 2013-02-20T08:33:23.983 回答