一、SQL、Linq、lamda表达式 同一功能不同写法

SQL

LINQ

Lambda

SELECT *

FROM HumanResources.Employee

from e in Employees

select e

Employees
   .Select (e => e)

SELECT e.LoginID, e.JobTitle

FROM HumanResources.Employee AS e

from e in Employees

select new {e.LoginID, e.JobTitle}

Employees
   .Select (
      e =>
         new
         {
            LoginID = e.LoginID,
            JobTitle = e.JobTitle
         }
   )

SELECT e.LoginID AS ID, e.JobTitle AS Title

FROM HumanResources.Employee AS e

from e in Employees

select new {ID = e.LoginID, Title = e.JobTitle}

Employees
   .Select (
      e =>
         new
         {
            ID = e.LoginID,
            Title = e.JobTitle
         }
   )

SELECT DISTINCT e.JobTitle

FROM HumanResources.Employee AS e

(from e in Employees

select e.JobTitle).Distinct()

Employees
   .Select (e => e.JobTitle)
   .Distinct ()

SELECT e.*

FROM HumanResources.Employee AS e

WHERE e.LoginID = 'test'

from e in Employees

where e.LoginID == "test"

select e

Employees
   .Where (e => (e.LoginID == "test"))

SELECT e.*

FROM HumanResources.Employee AS e

WHERE e.LoginID = 'test' AND e.SalariedFlag = 1

from e in Employees

where e.LoginID == "test" && e.SalariedFlag

select e

Employees
   .Where (e => ((e.LoginID == "test") && e.SalariedFlag))

SELECT e.*
FROM HumanResources.Employee AS e

WHERE e.VacationHours >= 2 AND e.VacationHours <= 10

from e in Employees

where e.VacationHours >= 2 && e.VacationHours <= 10

select e

Employees
   .Where (e => (((Int32)(e.VacationHours) >= 2) && ((Int32)(e.VacationHours) <= 10)))

SELECT e.*

FROM HumanResources.Employee AS e
ORDER BY e.NationalIDNumber

from e in Employees

orderby e.NationalIDNumber

select e

Employees
   .OrderBy (e => e.NationalIDNumber)

SELECT e.*

FROM HumanResources.Employee AS e

ORDER BY e.HireDate DESC, e.NationalIDNumber

from e in Employees

orderby e.HireDate descending, e.NationalIDNumber

select e

Employees
   .OrderByDescending (e => e.HireDate)
   .ThenBy (e => e.NationalIDNumber)

SELECT e.*
FROM HumanResources.Employee AS e

WHERE e.JobTitle LIKE 'Vice%' OR SUBSTRING(e.JobTitle, 0, 3) = 'Pro'

from e in Employees

where e.JobTitle.StartsWith("Vice") || e.JobTitle.Substring(0, 3) == "Pro"

select e

Employees
   .Where (e => (e.JobTitle.StartsWith ("Vice") || (e.JobTitle.Substring (0, 3) == "Pro")))

SELECT SUM(e.VacationHours)

FROM HumanResources.Employee AS e

Employees.Sum(e => e.VacationHours);

SELECT COUNT(*)

FROM HumanResources.Employee AS e

Employees.Count();

SELECT SUM(e.VacationHours) AS TotalVacations, e.JobTitle

FROM HumanResources.Employee AS e

GROUP BY e.JobTitle

from e in Employees

group e by e.JobTitle into g

select new {JobTitle = g.Key, TotalVacations = g.Sum(e => e.VacationHours)}

Employees
   .GroupBy (e => e.JobTitle)
   .Select (
      g =>
         new
         {
            JobTitle = g.Key,
            TotalVacations = g.Sum (e => (Int32)(e.VacationHours))
         }
   )

SELECT e.JobTitle, SUM(e.VacationHours) AS TotalVacations

FROM HumanResources.Employee AS e

GROUP BY e.JobTitle

HAVING e.COUNT(*) > 2

from e in Employees

group e by e.JobTitle into g

where g.Count() > 2

select new {JobTitle = g.Key, TotalVacations = g.Sum(e => e.VacationHours)}

Employees
   .GroupBy (e => e.JobTitle)
   .Where (g => (g.Count () > 2))
   .Select (
      g =>
         new
         {
            JobTitle = g.Key,
            TotalVacations = g.Sum (e => (Int32)(e.VacationHours))
         }
   )

SELECT *

FROM Production.Product AS p, Production.ProductReview AS pr

from p in Products

from pr in ProductReviews

select new {p, pr}

Products
   .SelectMany (
      p => ProductReviews,
      (p, pr) =>
         new
         {
            p = p,
            pr = pr
         }
   )

SELECT *

FROM Production.Product AS p

INNER JOIN Production.ProductReview AS pr ON p.ProductID = pr.ProductID

from p in Products

join pr in ProductReviews on p.ProductID equals pr.ProductID

select new {p, pr}

Products
   .Join (
      ProductReviews,
      p => p.ProductID,
      pr => pr.ProductID,
      (p, pr) =>
         new
         {
            p = p,
            pr = pr
         }
   )

SELECT *

FROM Production.Product AS p

INNER JOIN Production.ProductCostHistory AS pch ON p.ProductID = pch.ProductID AND p.SellStartDate = pch.StartDate

from p in Products

join pch in ProductCostHistories on new {p.ProductID, StartDate = p.SellStartDate} equals new {pch.ProductID, StartDate = pch.StartDate}

select new {p, pch}

Products
   .Join (
      ProductCostHistories,
      p =>
         new
         {
            ProductID = p.ProductID,
            StartDate = p.SellStartDate
         },
      pch =>
         new
         {
            ProductID = pch.ProductID,
            StartDate = pch.StartDate
         },
      (p, pch) =>
         new
         {
            p = p,
            pch = pch
         }
   )

SELECT *

FROM Production.Product AS p

LEFT OUTER JOIN Production.ProductReview AS pr ON p.ProductID = pr.ProductID

from p in Products

join pr in ProductReviews on p.ProductID equals pr.ProductID

into prodrev

select new {p, prodrev}

Products
   .GroupJoin (
      ProductReviews,
      p => p.ProductID,
      pr => pr.ProductID,
      (p, prodrev) =>
         new
         {
            p = p,
            prodrev = prodrev
         }
   )

SELECT p.ProductID AS ID

FROM Production.Product AS p

UNION

SELECT pr.ProductReviewID

FROM Production.ProductReview AS pr

(from p in Products

select new {ID = p.ProductID}).Union(

from pr in ProductReviews

select new {ID = pr.ProductReviewID})

Products
   .Select (
      p =>
         new
         {
            ID = p.ProductID
         }
   )
   .Union (
      ProductReviews
         .Select (
            pr =>
               new
               {
                  ID = pr.ProductReviewID
               }
         )
   )

SELECT TOP (10) *

FROM Production.Product AS p

WHERE p.StandardCost < 100

(from p in Products

where p.StandardCost < 100

select p).Take(10)

Products
   .Where (p => (p.StandardCost < 100))
   .Take (10)

SELECT *

FROM [Production].[Product] AS p

WHERE p.ProductID IN(

SELECT pr.ProductID

FROM [Production].[ProductReview] AS [pr]

WHERE pr.[Rating] = 5

)

from p in Products

where (from pr in ProductReviews

where pr.Rating == 5

select pr.ProductID).Contains(p.ProductID)

select p

Products
   .Where (
      p =>
         ProductReviews
            .Where (pr => (pr.Rating == 5))
            .Select (pr => pr.ProductID)
            .Contains (p.ProductID)
   )

二、同一功能的几种不同写法的实例

1、简单的函数计算(count,min,max,sum)

 
C# 代码   复制

            //1

            ////获取最大的rpId
var ss = (from r in db.Am_recProScheme
select r).Max(p => p.rpId);
////获取最小的rpId
var ss = (from r in db.Am_recProScheme
select r).Min(p => p.rpId);
//获取结果集的总数
var ss = (from r in db.Am_recProScheme
select r).Count();
//获取rpId的和
var ss = (from r in db.Am_recProScheme
select r).Sum(p => p.rpId);


//2
var ss1 = db.Am_recProScheme.Max(p=>p.rpId);
var ss1 = db.Am_recProScheme.Min(p => p.rpId);
var ss1 = db.Am_recProScheme.Count() ;
var ss1 = db.Am_recProScheme.Sum(p => p.rpId);
Response.Write(ss);

//3
string sssql = "select max(rpId) from Am_recProScheme";
sssql = "select min(rpId) from Am_recProScheme";
sssql = "select count(1) from Am_recProScheme";
sssql = "select sum(rpId) from Am_recProScheme";

2、排序order by desc/asc

 
C# 代码   复制

          var ss = from r in db.Am_recProScheme

                     where r.rpId > 10

                     orderby r.rpId descending  //倒序

                     //  orderby r.rpId ascending   //正序

                     select r;

          //正序

           var ss1 = db.Am_recProScheme.OrderBy(p => p.rpId).Where(p => p.rpId > 10).ToList();

          //倒序

           var ss2 = db.Am_recProScheme.OrderByDescending(p => p.rpId).Where(p => p.rpId > 10).ToList();

          string sssql = "select * from Am_recProScheme where rpid>10 order by rpId [desc|asc]";

3、top

 
 
C# 代码   复制

          //1

          //如果取最后一个可以按倒叙排列再取值

           var ss = (from r in db.Am_recProScheme select r).FirstOrDefault();

          //2

          string sssql = "select top(1) * from Am_recProScheme";

4、跳过前面多少条数据取余下的数据

 
 
C# 代码   复制

             //1

           var ss = (from r in db.Am_recProScheme

                      orderby r.rpId descending

                      select r).Skip(10); //跳过前10条数据,取10条之后的所有数据

             //2

           var ss1 = db.Am_recProScheme.OrderByDescending(p => p.rpId).Skip(10).ToList();

           //3

           string sssql = "select * from  (select ROW_NUMBER()over(order by rpId desc) as rowNum, * from [Am_recProScheme]) as t where rowNum>10";

5、分页数据查询

 
 
C# 代码   复制

             //1

           var ss = (from r in db.Am_recProScheme

                      where r.rpId > 10

                      orderby r.rpId descending

                      select r).Skip(10).Take(10); //取第11条到第20条数据

            //2 Take(10): 数据从开始获取,获取指定数量(10)的连续数据

            var ss1 = db.Am_recProScheme.OrderByDescending(p => p.rpId).Where(p => p.rpId > 10).Skip(10).Take(10).ToList();

           //3

           string sssql = "select * from  (select ROW_NUMBER()over(order by rpId desc) as rowNum, * from [Am_recProScheme]) as t where rowNum>10 and rowNum<=20";

6、包含,类似like '%%'

 
 
C# 代码   复制

              //1

            var ss = from r in db.Am_recProScheme

                     where r.SortsText.Contains("张")

                     select r;

            //2

            var ss1 = db.Am_recProScheme.Where(p => p.SortsText.Contains("张")).ToList();

            //3

            string sssql = "select * from Am_recProScheme where SortsText like '%张%'";

7、分组group by

 
 
C# 代码   复制

              //1

            var ss = from r in db.Am_recProScheme

                     orderby r.rpId descending

                     group r by r.recType into n

                     select new

                     {
n.Key, //这个Key是recType
rpId = n.Sum(r => r.rpId), //组内rpId之和
MaxRpId = n.Max(r => r.rpId),//组内最大rpId
MinRpId = n.Min(r => r.rpId), //组内最小rpId
};
foreach (var t in ss)
{
Response.Write(t.Key + "--" + t.rpId + "--" + t.MaxRpId + "--" + t.MinRpId);
}

//2
var ss1 = from r in db.Am_recProScheme
orderby r.rpId descending
group r by r.recType into n
select n;
foreach (var t in ss1)
{
Response.Write(t.Key + "--" + t.Min(p => p.rpId));
}

//3
var ss2 = db.Am_recProScheme.GroupBy(p => p.recType);
foreach (var t in ss2)
{
Response.Write(t.Key + "--" + t.Min(p => p.rpId));
}

//4
string sssql = "select recType,min(rpId),max(rpId),sum(rpId) from Am_recProScheme group by recType";

8、连接查询 

 
 
C# 代码   复制

            //1

            var ss = from r in db.Am_recProScheme

                     join w in db.Am_Test_Result on r.rpId equals w.rsId

                     orderby r.rpId descending

                     select r;

            //2

            var ss1 = db.Am_recProScheme.Join(db.Am_Test_Result, p => p.rpId, r => r.rsId, (p, r) => p).OrderByDescending(p => p.rpId).ToList();

            //3

            string sssql = "select r.* from  [Am_recProScheme] as r inner join [dbo].[Am_Test_Result] as t on r.[rpId] = t.[rsId] order by r.[rpId] desc";

9、sql中的In

 
 
C# 代码   复制

              //1

            var ss = from p in db.Am_recProScheme

                              where (new int?[] { 24, 25,26 }).Contains(p.rpId)
select p;
foreach (var p in ss)
{
Response.Write(p.Sorts);
}

//2
string st = "select * from Am_recProScheme where rpId in(24,25,26)";

SQL、Linq、lamda表达式 同一功能不同写法的更多相关文章

  1. SQL/LINQ/Lamda 写法[转发]

    SQL LINQ Lambda SELECT * FROM HumanResources.Employee from e in Employees select e Employees   .Sele ...

  2. lamda表达式的两种写法

    public class Test{ public synchronized void test1(){ System.out.println("test1 start........... ...

  3. SQL Linq lamda区别

    SQL LINQ Lambda SELECT * FROM HumanResources.Employee from e in Employees select e Employees   .Sele ...

  4. SQL/LINQ/Lamda

    SQL LINQ Lambda SELECT * FROM HumanResources.Employee from e in Employees select e Employees   .Sele ...

  5. Linq lamda表达式Single和First方法

      让我们来看看如何对一个整数数组使用 Single 操作符.这个整数数组的每个元素代表 2 的 1 到 10 次方.先创建此数组,然后使用 Single 操作符来检索满足 Linq Lambda表达 ...

  6. C#DataTable 使用GroupBy方法的lamda 表达式和Linq语句写法

    https://www.cnblogs.com/johnblogs/p/6006867.html DataTable ds = new DataTable(); //1.lamda 表达式写法(推荐) ...

  7. C# Linq及Lamda表达式实战应用之 GroupBy 分组统计

    在项目中做统计图表的时候,需要对查询出来的列表数据进行分组统计,首先想到的是避免频繁去操作数据库可以使用 Linq eg: //例如对列表中的Cu元素进行按年GroupBy分组统计 //包含年份,平均 ...

  8. Linq和Lamda表达式的简单处理方式

    一 什么是LINQ? LINQ即Language Integrated Query(语言集成查询),LINQ是集成到C#和Visual Basic.NET这些语言中用于提供查询数据能力的一个新特性. ...

  9. c# Linq及Lamda表达式应用经验之 GroupBy 分组

    示例1: GroupBy 分组在List<>泛型中的应用 原表: 按姓名Nam 分组后结果: 对DATATABLE 进行LAMDA查询时必须在项目的引用中添加 System.Data.Da ...

随机推荐

  1. opencart在空间中安装出错,连接不上mysql

    客户要求,要在国外某空间安装opencart.话说opencart根本没怎么搞过,也不太清楚,php也是半吊子,临时看了几天,硬着头皮上把. 出错,安装进行到数据库连接设置的时候,死活连接不上,开始以 ...

  2. Lua学习----Lua的表达式

    前言 Lua的运算符和其他语言基本类似.但也有一点点区别 1.算术运算符 Lua的算术运算符加入了指数运算符^ print(2 ^ 10) -->打印 1024. 求2的10次方 2.关系运算符 ...

  3. WCF服务客户端首页调用慢的问题处理

    场景: WCF服务架设于IIS服务中,走TCP协议.客户端首次调用特别慢,第一次加载完后,都正常. 解决: 把服务中需要序列化的模型所在的工程 > 属性 > 生成 > 生成序列化程序 ...

  4. SQLite 函数大全

    http://blog.sina.com.cn/s/blog_48e2ea3401012031.html

  5. MVC3升级为MVC4

    在程序包管理控制台输入 Install-Package UpgradeMvc3ToMvc4 等待 升级完成

  6. 用openvswitch配置跨节点的docker网络环境

    在一篇随笔中,我们已经尝试了在不依赖工具的情况下设置docker的ip,连我都想吐槽,MD单机都这么麻烦,在多机的环境中岂不是要了我的小命! 本文就是为了多机环境中各个节点的容器通信而做的,网络拓朴如 ...

  7. 转I2s

    转自http://blog.csdn.net/ce123/article/details/6919954 I2S音频总线学习(二)I2S总线协议 一.I2S总线概述 音响数据的采集.处理和传输是多媒体 ...

  8. jquery mobile radio,checkbox button 样式设置

    <label><input type=checkbox ></label>,<input type=checkbox id="checkbox &q ...

  9. JavaScript学习基础篇【第1篇】: JavaScript 入门

    JavaScript 快速入门 JavaScript代码可以直接嵌在网页的任何地方,不过通常我们都把JavaScript代码放到<head>中,由<script>...< ...

  10. OpenGL学习笔记3——缓冲区对象

    在GL中特别提出了缓冲区对象这一概念,是针对提高绘图效率的一个手段.由于GL的架构是基于客户——服务器模型建立的,因此默认所有的绘图数据均是存储在本地客户端,通过GL内核渲染处理以后再将数据发往GPU ...