我如何Group
List<Person> Persons
Person.Age
使用LINQ
并创建新的List<List<Person>> PersonsByAge
?
public class Person
{
public string Name;
public int Age
}
答案 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();
这会创建List
个List<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();