這里主要是將數據庫中的常用操作用LAMBDA表達式重新表示了下,用法不多,但相對較常用,等有時間了還會擴展,並將查詢語句及LINQ到時也一並重新整理下:
1.select語句:books.Select(p=>new { p.Title, p.UnitPrice, p.Author});//需用匿名方式
2.where語句:books.Where(p=>p.UnitPrice==100&&p.Title=”ABC”);
補充:
像數據庫中的LIKE ‘%c++%’,LAMBDA中用p.Title.Contains(“c++”)表示;
像數據庫中的LIKE ‘c%’,LAMBDA中用p.Title.StartWith(“c”)表示;
像數據庫中的LIKE ‘%c’,LAMBDA中用p.Title.EndsWith(“c”)表示;
Where的另一種表現形式:
books.Where(p=>{
var ret = p.UnitPrice>30&&p.Title.Contains(“c++”);
return ret;
});
3.排序語句:
像數據庫中order by 升序:
通過 “對象.OrderBy(p=>p.UnitPrice)”實現
像數據庫中order by 降序:
通過 “對象.OrderByDescending(p=>p.UnitPrice)”實現
像數據庫中order by UnitPrice desc,Title asc:
通過 ”對象.OrderByDescending(p=>p.UnitPrice).ThenBy(p=>p.Title)”
反過來則是: ”對象.OrderBy(p=>p.UnitPrice).ThenByDescending(p=>p.Title)”
4.組函數:
var max = books.Where(p => p.CategoryId == 1001).Max(p => p.UnitPrice);
var min = books.Min(p => p.UnitPrice);
var count = books.Count( );
var avg = books.Average(p => p.UnitPrice);
var sum = books.Sum(p => p.UnitPrice);
注意,上面這些獲得的東西,不是對象,是單個值
5. GROUP BY函數
// select categoryid,max(unitpirce) from books group by categoryid having max(unitprice)>50
var list6 = books.GroupBy(p => p.CategoryId).Where(p=>p.Max(q=>q.UnitPrice)>50);
foreach (var item in list6)
{
Response.Write(string.Format("
- 類別編號:{0},最高價{1}
- ",
item.Key,item.Max(p=>p.UnitPrice)));
}
6. TOP函數
//取一個范圍 如3,5
var list7 = books.Skip(2).Take(3).Select(p => new { p.Title, p.CategoryId, p.UnitPrice });
// select top 5
var list7 = books.Take(5).OrderByDescending(p => p.UnitPrice)
.Select(p => new { p.CategoryId, p.UnitPrice, p.Title, p.Author });
7.union 函數
books.Where(p => p.CategoryId == 1001).Select(p => new { p.CategoryId, p.UnitPrice, p.Title, p.Author }).Union(books.Where(p => p.CategoryId == 1002).Select(p => new { p.CategoryId, p.UnitPrice, p.Title, p.Author }));
這里的Select子句中的列需對應,跟數據庫中是一樣的
8.Join方法,用於實現數據庫中雙表連接查詢
//select a.title,a.unitprice,a.categoryid,b.id,b.name from books a,category b
//where a.categoryid=b.id and b.name=‘數據庫’
books.Join(cates.Where(m => m.Name == "數據庫"),p => p.CategoryId, q => q.ID, (a, b) => new { a.Title, a.UnitPrice, a.CategoryId, b.ID, b.Name });
說明:
Join()方法的調用對象類似於在SQL語句中第一張表的表名
而Join()方法的第一個形參是第二張表表名的Where條件
Join()方法的第二和第三個參數分別表示第一張表與第二張表的關聯字段
Join()方法的第四個參數表示從兩表中需要獲取的字段,(a, b)分別表示第一張表和第二張表