我有一组Person
pocos,填充如下。我正在尝试按省按字母顺序显示它们,然后按省内的LastName显示。我正在使用分组,我可以将省份整理好,只是不确定如何在省内的人群中订购。
此代码:
Person[] people = new Person[]
{
new Person() { FirstName = "Tony", LastName = "Montana", Age = 39, HomeProvince = "Ontario" },
new Person() { FirstName = "Bill", LastName = "Smith", Age = 23, HomeProvince = "Ontario" },
new Person() { FirstName = "Jane", LastName = "Doe", Age = 23, HomeProvince = "Alberta" },
new Person() { FirstName = "John", LastName = "Doe", Age = 23, HomeProvince = "Alberta" },
new Person() { FirstName = "Alex", LastName = "DeLarge", Age = 19, HomeProvince = "British Columbia" },
new Person() { FirstName = "Travis", LastName = "Bickle", Age = 42, HomeProvince = "Quebec" },
new Person() { FirstName = "Ferris", LastName = "Beuller", Age = 17, HomeProvince = "Manitoba" },
new Person() { FirstName = "Maggie", LastName = "May", Age = 23, HomeProvince = "Ontario" },
new Person() { FirstName = "Mickey", LastName = "Mouse", Age = 93, HomeProvince = "Alberta" },
new Person() { FirstName = "Frank", LastName = "Darabont", Age = 49, HomeProvince = "Ontario" }
};
var query =
from person in people
group person by person.HomeProvince into g
orderby g.Key
select new { Province = g.Key, People = g };
foreach (var prov in query)
{
Console.WriteLine("{0}: ", prov.Province);
foreach (var person in prov.People)
{
Console.WriteLine(" {0} {1}, {2}", person.FirstName, person.LastName, person.Age);
}
}
给我这个输出:
Alberta:
Jane Doe, 23
John Doe, 23
Mickey Mouse, 93
British Columbia:
Alex DeLarge, 19
Manitoba:
Ferris Beuller, 17
Ontario:
Tony Montana, 39
Bill Smith, 23
Maggie May, 23
Frank Darabont, 49
Quebec:
Travis Bickle, 42
正如您所看到的,省份按字母顺序排列,但我如何列出省内的人(即安大略省我想要这个订单:Darabont,Montana,May,Smith)。
答案 0 :(得分:2)
假设您想要LastName的字母顺序,请更改此:
select new { Province = g.Key, People = g };
为:
select new { Province = g.Key, People = g.OrderBy(p => p.LastName) };
但请注意,您的示例“Darabont,Montana,May,Smith”并不完全按字母顺序排列。我认为这只是你的错误,但如果这实际上是你想要的订单,请解释你用来生成这个订单的规则。
答案 1 :(得分:0)
应该能够在select语句之后到orderby(person => person.LastName);