C#中Lambda表达式常用写法 快收藏

C#中Lambda表达式常用写法,平时使用容易忘记,这里重新整理下:

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)分别表示第一张表和第二张表