将List <object>分组到List <list <object>&gt; </list <object> </object>

时间:2014-06-22 17:22:05

标签: c# linq list

我如何Group List<Person> Persons Person.Age使用LINQ并创建新的List<List<Person>> PersonsByAge

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

2 个答案:

答案 0 :(得分:4)

GroupBy和几个ToList来电应该可以胜任:

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

答案 1 :(得分:0)

一种可能的解决方案如下:

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

这会创建ListList<Person>个项目。

另一种可能性是创建一个表示(强类型)List<List<Person>>结构的类:

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

并填写如下:

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