Domanda

Lets say I have a class called Person:

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

And a list of persons:

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

What I want to have is a (new or old with a new property) list that groups the person by age, first name and last name AND I also want to know how many times that object has been grouped.

So the result of the above would be:

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

Soluzione

Simple:

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

Altri suggerimenti

Just before I posted I saw answer already from JustAnotherUserYouMayKnow, so was going to cancel, but am posting anyway just to show same result using only the GroupBy, with the resultSelector parameter (instead of separate projection)

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

Non-proc alternative:

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()});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top