Vahid
Vahid

Reputation: 5444

Group a List<Object> into List<List<Object>>

How can I Group a List<Person> Persons by Person.Age using LINQ and create a new List<List<Person>> PersonsByAge ?

public class Person
{
    public string Name;
    public int Age
}

Upvotes: 0

Views: 83

Answers (2)

jakobbotsch
jakobbotsch

Reputation: 6337

A GroupBy and a few ToList calls should do the job:

List<Person> persons = ...;
List<List<Person>> byAge = persons
                           .GroupBy(p => p.Age)
                           .Select(ps => ps.ToList())
                           .ToList();

Upvotes: 4

keenthinker
keenthinker

Reputation: 7820

One possible solution would look like this:

var persons = new List<Person>
{
    new Person { Age = 20 },
    new Person { Age = 30 },
    new Person { Age = 20 },
    new Person { Age = 40 },
    new Person { Age = 50 },
    new Person { Age = 50 },
    new Person { Age = 20 }
};

var result =    from person in persons
                group person by person.Age into g
                select g.ToList();
var listOfListOfPersons = result.ToList();

This would create a List holding List<Person> items.

Yet another possibility would be to create a class representing the (strongly typed) List<List<Person>> structure:

public class Persons
{
    public List<Person> Entries { get; set; }
}
public class Person
{
    public Int32 Age { get; set; }
}

and fill it like this:

var result =    from person in persons
                group person by person.Age into g
                select new Persons
                {
                    Entries = g.ToList()
                };
var listOfListOfPersons = result.ToList();

Upvotes: 0

Related Questions