C# 排序查詢結(jié)果
用where子句(或者WhereO方法調(diào)用)找到了感興趣的數(shù)據(jù)后,LINQ還可以方便地對得到的數(shù)據(jù)執(zhí)行進(jìn)一步處理,例如,重新排列結(jié)果的順序。下面的示例將按字母順序給第一個(gè)查詢的結(jié)果排序。
試一試給查詢結(jié)果排序:BeginningCSharp7_22_5_OrderQueryResults\Program.cs
按照下面的步驟在Visual Studio 2017中創(chuàng)建示例。
(1)可以修改QuerySyntax示例,或者在C:\BeginningCSharp7\Chapter22目錄中創(chuàng)建一個(gè)新的控制臺(tái)應(yīng)用程序項(xiàng)目 BeginningCSharp7_22_5_OrderQueryResults。
(2)打開主源文件Program.cs。與以前一樣,Visual Studio 2017會(huì)自動(dòng)在Program.cs 中包含using System. Linq; 名稱空間指令。
(3)在Progranj.cs的Main()方法中添加如下代碼:
static void Main{string[] args)
{
string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe",
"Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich11," Singh", "Samba", "Fatimah" };
var queryResults =
from n in names
where n.StartsWith("S")
orderby n
select n;
WriteLine("Names beginning with S ordered alphabetically:");
foreach {var item in queryResults) {
WriteLine(item);
}
Write ("Program finished, press Enter/Return to continue:");
ReadLine();
}
(4)編譯并執(zhí)行程序。結(jié)果是以S開頭的names列表,且按字母順序排序,如下所示:
Names beginning with S:
Samba
Singh
Small
Smith
Smythe
Program finished, press Enter/Return to continue:
示例說明
這個(gè)程序與前一個(gè)程序幾乎相同,只是在查詢語句中增加了一行代碼
var queryResults =
from n in names
where n.StartsWith("S")
orderby n
select n;
點(diǎn)擊加載更多評論>>