美文网首页
C# LINQ和Lambda表达式详解

C# LINQ和Lambda表达式详解

作者: 夜藍 | 来源:发表于2023-11-26 16:35 被阅读0次


    (1) 简单的查询语句

    1 Linq语法:

    2  var data=from a in db.Areas select a ;

    3 Lamda语法:

    4  var data=db.Areas;

    5 sql语法:

    6  string sqlStr=" SELECT * FROM Areas  ";

    (2) 简单的WHERE语句

    1 Linq语法:

    2  var data=from a in db.orderInfo where a.orderId > 20 select a ;

    3 Lamda语法:

    4  var data=db.orderInfo.Where( t=>t.orderId > 20 ) ;

    5 sql语法:

    6  string sqlStr=" SELECT * FROM orderInfo WHERE orderId > 20 ";

    (3) 关于“COUNT、SUM、MIN、MAX”函数的语句

    1 Linq语法:

    2  var data=( from a in db.orderInfo select a ).Max( p=>p.orderId ) ;//查询该表中最大编号Id

    3  var data=( from a in db.orderInfo select a ).Min( p=>p.orderId ) ;//查询该表中最小编号Id

    4  var data=( from a in db.orderInfo select a ).Count() ;//查询该表数据总条数

    5  var data=( from a in db.orderInfo select a ).Sum( p=>p.orderMoney ) ;//查询该表中所有消费额的总数(求和)

    6 Lamda语法:

    7  var data=db.orderInfo.Max( t=>t.orderId );//查询该表中最大编号Id

    8  var data=db.orderInfo.Min( t=>t.orderId );//查询该表中最小编号Id

    9  var data=db.orderInfo.Count();//查询该表数据总条数

    10  var data=db.orderInfo.Sum( t=>t.orderMoney );//查询该表中所有消费额的总数(求和)

    11 sql语法:

    12  string sqlStr=" SELECT MAX(orderId) FROM orderInfo ";

    13  string sqlStr=" SELECT MIN(orderId) FROM orderInfo ";

    14  string sqlStr=" SELECT COUNT(*) FROM orderInfo ";

    15  string sqlStr=" SELECT SUM(orderMoney ) FROM orderInfo ";

    (4) 关于数据排序的语句

    1 Linq语法:

    2  var data=from a in db.orderInfo where a.orderId > 20 orderby a.orderId descending select a ;//倒序排序,升序可用ascending关键字

    3 Lamda语法:

    4  //情况一,根据单字段排序:

    5  var data=db.orderInfo.OrderByDescending( t=>t.orderId ).Where( t=>t.orderId > 20 ) .ToList();//倒序排序,升序可用OrderBy关键字

    6  //情况二,根据多字段主次排序:

    7  var priceMonthEntities = priceMonthApp.GetList().OrderBy(t => t.F_Year).ThenBy(t => t.F_Month).ToList();//先按年升序,再按月升序

    8 sql语法:

    9  string sqlStr=" SELECT * FROM orderInfo WHERE orderId > 20 ORDER BY orderId DESC  ";//倒序排序,升序可用ASC关键字

    (5) 关于分页查询的语句

    1 Linq语法:

    2  var data=( from a in db.orderInfo select a ) .Skip((pageIndex-1) * pageSize).Take(pageSize).ToList();

    3 Lamda语法:

    4  var data=db.orderInfo.Skip((pageIndex-1)* pageSize).Take(pageSize).ToList();;//pageIndex:当前页码,pageSize:分页数据显示条数

    5 sql语法:

    6  string sqlStr="SELECT TOP pageSize * FROM orderInfo WHERE orderId NOT IN(SELECT TOP( ( pageIndex - 1) * pageSize) orderId FROM orderInfo)";

    (6) 关于模糊查询(like)的语句

    1 Linq语法:

    2  var data= from a in db.orderInfo where a.orderId.Contains(1) select a;//使用Contains关键字进行模糊匹配

    3 Lamda语法:

    4  var data=db.orderInfo.Where(t=>t.F_UserId.Contains("1")).ToList();//使用Contains关键字进行模糊匹配

    5 sql语法:

    6  string sqlStr="SELECT * FROM orderInfo WHERE orderId LIKE '%12%'";//使用like关键字进行模糊匹配

    (7) 关于分组查询的语句

    1 Linq语法:

    2  var data= from a in db.orderInfo orderby a.orderId descending

    3            group a by a.orderType into s select new{

    4            s.key,//分组字段

    5            s.sMoney=s.Sum(a=>a.orderMoney),//分组后算出总的消费额

    6            s.maMoney=s.Max(a=>a.orderMoney),//分组后算出最大的消费额

    7            s.miMoney=s.Min(a=>a.orderMoney)//分组后算出最小的消费额

    8            };

    9 Lamda语法:

    10  //使用GroupBy关键字进行分组查询(单个字段)

    11  var data=db.orderInfo.GroupBy(p => p.recType).Select(t=>t.Key).ToList();

    12  //使用GroupBy关键字进行分组查询(多个字段)

    13  var data=db.orderInfo.GroupBy(p =>new{ p.recType,p.orderId}).Select(t=>new{ recType=t.Key.recType,orderId=t.Key.orderId}).ToList();

    14 sql语法:

    15  string sqlStr="SELECT orderType , SUM(orderMoney), MAX(orderMoney), MIN(orderMoney) FROM orderInfo GROUP BY orderType";

    (8) 关于多表关联查询的语句

    1 Linq语法:

    2  //使用join关键字进行表连接

    3  var data= from a in db.orderInfo join e in  db.orderType on a.orderTypeId equals e.id select r ;

    4  var query=from t in db.orderInfo join s in db.orderType on t.orderTypeId equals s.id select

    5  new {

    6        orderId=t.id,

    7        orderTypeName=s.name,

    8        ...

    9  }

    10 Lamda语法:

    11  var data=db.orderInfo.Join(db.orderType,t=>t.orderTypeId,s=>s.id,(t,s)=>t).OrderByDescending(t=>t.orderId).

    12  Select(

    13            t=> new{

    14              orderId=t.t.id,

    15              orderTypeName=t.s.name,

    16              ...

    17          }).ToList(); //使用Join关键字进行表连接

    18 EF Core中的写法:

    19  var data=db.orderInfo.Join(db.orderType,t=>t.orderTypeId,s=>s.id,(t,s)=>new{

    20  orderId=s.Id,

    21  .....

    22  }).toList();

    23 sql语法:(sql语句表关联有多种方法,在此只举一例)

    24  string sqlStr="SELECT * FROM orderInfo o ,orderType t WHERE o.orderTypeId=t.id ORDER BY t.createDate";

    (9) 关于in查询的语句

    1 Linq语法:

    2  var data= from a in db.orderInfo where (new int?[2213,43311,32422]).Contains(a.orderId) select a ;

    3 Lamda语法:

    4  var data=db.orderInfo.Where(t=>(new int?[2213,43311,32422]).Contains(t.orderId)).ToList();

    5 sql语法:

    6  string sqlStr="SELECT * FROM orderInfo WHERE orderId IN (2213,43311,32422)";

    (10) 关于去重查询的语句

    1 Linq语法:

    2  var data= from a in db.orderInfo group p by new {a.orderTypeId} into _group select _group.FirstOrDefault(); //使用group关键字进行表数据去重

    3  var data= from a in db.orderInfo group p by new {a.orderTypeId,...} into _group select _group.FirstOrDefault(); //使用group关键字对多个字段进行表数据去重

    4 Lamda语法:

    5  //单个去重:

    6  var data=db.orderInfo.GroupBy(t=>t.orderTypeId).Select(r => r.First()).ToList(); //使用GroupBy关键字进行表数据去重

    7  var data=db.orderInfo.DistinctBy(t=>t.orderTypeId).ToList(); //使用DistinctBy关键字进行表数据去重

    8  //多个字段去重:

    9  var data=db.orderInfo.GroupBy(t=>new{t.orderTypeId,...}).Select(r => r.First()).ToList(); //使用GroupBy关键字对多个字段进行表数据去重

    10  var data=db.orderInfo.DistinctBy(t=>new{t.orderTypeId,...}).ToList(); //使用DistinctBy关键字对多个字段进行表数据去重

    11 sql语法:

    12  string sqlStr="SELECT DISTINCT orderTypeId  FROM orderInfo";//使用DISTINCT关键字进行表数据去重

    13  string sqlStr="SELECT orderTypeId FROM orderInfo GROUP BY orderTypeId";//使用GROUP BY关键字进行表数据去重

    (11) 内连接 INNER JOIN

    1 Linq语法:

    2 var ss = from r in db.Am_recProScheme

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

    4          orderby r.rpId descending

    5          select r;

    6 Lamda语法:

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

    8 sql语法:

    9 string sssql = "SELECT r.* FROM Am_recProScheme AS r INNER JOIN Am_Test_Result AS t ON r.[rpId] = t.[rsId] ORDER BY r.[rpId] DESC";

    (12) 左连接 LEFT JOIN

    1 //两个DataTable关联,查找只在第一个表中的数据

    2 static void Main(string[] args)

    3 {

    4    DataTable dt1 = new DataTable("Ta");

    5    DataTable dt2 = new DataTable("Tb");

    6    dt1.Columns.Add("ID", typeof(int));

    7    dt1.Columns.Add("Name", typeof(string));

    8    dt1.Rows.Add(1, "小明");

    9    dt1.Rows.Add(2, "小红");

    10    dt1.Rows.Add(3, "小黑");

    11    dt2.Columns.Add("ID", typeof(int));

    12    dt2.Columns.Add("Name", typeof(string));

    13    dt2.Rows.Add(1, "小黄");

    14    dt2.Rows.Add(2, "小红");

    15    dt2.Rows.Add(3, "小强");

    16    方法一:Linq语法

    17    var query = from q1 in dt1.AsEnumerable()

    18                join q2 in dt2.AsEnumerable()

    19                on q1.Field<string>("Name") equals q2.Field<string>("Name") into tmp

    20                from q3 in tmp.DefaultIfEmpty()

    21                where q3 == null

    22                select new

    23                {

    24                    ID = q1.Field<int>("ID"),

    25                    Name = q1.Field<string>("Name")

    26                };

    27    方法二:Lamda语法

    28    var query = dt1.AsEnumerable().GroupJoin(

    29        dt2.AsEnumerable(),

    30        x => x.Field<string>("Name"),

    31        y => y.Field<string>("Name"),

    32        (x, y) => y.DefaultIfEmpty(). Where(w => w == null).

    33        Select(z => new { ID = x.Field<int>("ID"), Name = x.Field<string>("Name") })

    34        ).SelectMany(x => x);

    35    foreach (var item in query)

    36    {

    37        Console.WriteLine($"ID={item.ID}    Name={item.Name}");

    38    }

    39    Console.Read();

    40 }

    (13) 三表连接

    1 SELECT id, name, jname, cname 

    2        FROM userinfo u 

    3        LEFT JOIN job j on u.job = j.jid 

    4        LEFT JOIN city c on u.city = c.cid 

    5

    6 var list = ( 

    7    from u in dc.userinfos 

    8        join j in dc.jobs on u.job equals j.jid into j_join 

    9    from x in j_join.DefaultIfEmpty() 

    10        join c in dc.cities on u.city equals c.cid into c_join 

    11    from v in c_join.DefaultIfEmpty() 

    12    select new 

    13    { 

    14        id = u.id, 

    15        name = u.name, 

    16        jname = x.jname, 

    17        cname = v.cname, 

    18        /*u1=u,x1=x,v1=v*/ 

    19        //不要用对象的方式 因为对象可能为null那么对象.属性就会抛异常 

    20    } 

    21    ).ToList(); 

    22     

    23    for (var i = 0; i < list.Count(); i++) 

    24    { 

    25        Console.WriteLine(list[i].name + '\t' + list[i].jname + '\t' + list[i].cname); //字段为null不报异常 

    26        //Console.WriteLine(list[i].u1.name+'\t'+list[i].x1.jname+'\t'+list[i].v1.cname+"\r\n"); //对象x1 v1 有可能为null 抛异常 

    27    } 

    28    Console.ReadLine();

    (14) 实例用法:

    1 //数据库 + 自定义名称 =new 数据库

    2 mydbDataContext con = new mydbDataContext();

    3 //模糊查询表达式中用.Contains

    4 con.car.Where(r=>r.name.Contains(TextBox1.Text.Trim())).ToList();

    5 //开头查用.StartWith

    6 con.car.Where(r => r.name.StartsWith(TextBox1.Text)).ToList();

    7 //结尾查用.EndWith

    8 con.car.Where(r => r.name.EndsWith(TextBox1.Text)).ToList();

    9 //最大值

    10 con.car.Max(r => r.price * r.oil).ToString();

    11 //最小值

    12 con.car.Min(r => r.price).ToString();

    13 //求和

    14 con.car.Sum(r => r.price).ToString();

    15 //平均值

    16 con.car.Average(r => r.price).ToString();

    17 //升序:

    18 con.car.OrderBy(r => r.price).ToList();

    19 //降序:

    20 con.car.OrderByDescending(r => r.price).ToList();

    21

    22 //上一页,下一页,组合查询:

    23 int PageCount = 5;//每页显示条数

    24 //上一页,PageCount_Label.Text为当前页码

    25 int pageNum = Convert.ToInt32(PageCount_Label.Text) - 1;

    26 Repeater1.DataSource = con.car.Skip((pageNum - 1) * PageCount).Take(PageCount);

    27 Repeater1.DataBind();

    28 PageCount_Label.Text = pageNum.ToString();

    29 //下一页

    30 int pageNum = Convert.ToInt32(PageCount_Label.Text) + 1;

    31 Repeater1.DataSource = con.car.Skip((pageNum - 1) * PageCount).Take(PageCount);

    32 Repeater1.DataBind();

    33 PageCount_Label.Text = pageNum.ToString();

    34 //组合查询的点击事件

    35 List<car> list = con.car.ToList();

    36 if (TextBox2.Text != "")

    37 {

    38    List<car> list1 = con.car.Where(r => r.name.Contains(TextBox2.Text)).ToList();

    39    list = list.Intersect(list1).ToList();

    40 }

    41 if (TextBox3.Text != "")

    42 {

    43    List<car> list1 = con.car.Where(r => r.oil == Convert.ToDecimal(TextBox3.Text)).ToList();

    44    list = list.Intersect(list1).ToList();

    45 }

    46 if (TextBox4.Text != "")

    47 {

    48    List<car> list1 = con.car.Where(r => r.powers == Convert.ToInt32(TextBox4.Text)).ToList();

    49    list = list.Intersect(list1).ToList();

    50 }

    51 Repeater1.DataSource = list;

    52 Repeater1.DataBind();

    相关文章

      网友评论

          本文标题:C# LINQ和Lambda表达式详解

          本文链接:https://www.haomeiwen.com/subject/zhbawdtx.html