.net中LAMBDA表達式經常使用寫法

這裏主要是將數據庫中的經常使用操做用LAMBDA表達式從新表示了下,用法很少,但相對較經常使用,等有時間了還會擴展,並將查詢語句及LINQ到時也一併從新整理下:c++

1.select語句:books.Select(p=>new { p.Title, p.UnitPrice, p.Author});//需用匿名方式數據庫

2.where語句:books.Where(p=>p.UnitPrice==100&&p.Title=」ABC」);函數

補充:spa

像數據庫中的LIKE ‘%c++%’,LAMBDA中用p.Title.Contains(「c++」)表示;orm

像數據庫中的LIKE ‘c%’,LAMBDA中用p.Title.StartWith(「c」)表示;對象

像數據庫中的LIKE ‘%c’,LAMBDA中用p.Title.EndsWith(「c」)表示;排序

Where的另外一種表現形式:ip

books.Where(p=>{string

    var ret = p.UnitPrice>30&&p.Title.Contains(「c++」);it

    return ret;

});

3.排序語句:

像數據庫中order by 升序:

經過 「對象.OrderBy(p=>p.UnitPrice)」實現

像數據庫中order by 降序:

經過 「對象.OrderByDescending(p=>p.UnitPrice)」實現

像數據庫中order by UnitPrice descTitle 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)分別表示第一張表和第二張表

相關文章
相關標籤/搜索