如何於LINQ使用類似TSQL的ROW_NUMBER
在TSQL中要產生Row Number,可以透過ROW_NUMBER函數,下列程式碼範例是用來查詢北風資料庫中的Customers Table,於原本的欄位中以CustomerID為排序條件產生列號:
1: select ROW_NUMBER() OVER (ORDER BY CustomerID) AS SN,*
2: from Customers
執行結果如下:
若要在LINQ語法中做到類似上述功能,可以以下列程式碼來完成:
1: using (DataClasses1DataContext context = new DataClasses1DataContext())
2: {
3: int i = 0;
4: var query = from p in context.Region.AsEnumerable()
5: select new { SN = ++i, p };
6: foreach (var item in query)
7: {
8: Response.Write(string.Format("{0},{1}<br/>", item.SN, item.p.RegionDescription));
9: }
10: }
11:
12: using (NorthwindEntities contxt = new NorthwindEntities())
13: {
14: int j = 1;
15: var query = from p in contxt.Customers.AsEnumerable()
16: select new { sn = j++, p};
17: foreach (var item in query)
18: {
19: Response.Write(string.Format("{0},{1}<br/>", item.sn, item.p.CompanyName));
20: }
21: }
【程式碼說明】
上述程式碼第1至10列為LINQ to SQL的表示方式,第12至21列為LINQ to Entity的標示方式,皆必須以AsEnumerable方法將之轉成對應的泛型型別之後才能在select敘述中自動產生序號。
參考資料: