日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

LINQ基礎之Join和UNION子句_C#教程

作者:農(nóng)碼一生 ? 更新時間: 2022-06-19 編程語言

Join子句

一、簡介

使用join子句可以將來自不同源序列并且在對象模型中沒有直接關系的元素相關聯(lián),唯一的要求是每個源中的元素需要共享某個可以進行比較以判斷是否相等的值,join子句使用特殊的equals關鍵字比較指定的鍵是否相等。

二、案例

內(nèi)部連接

var innerJoinQuery =
              from category in categories
              join prod in products on category.ID equals prod.CategoryID
                      select new { ProductName = prod.Name, Category = category.Name };

分組連接

var innerGroupJoinQuery =
 from category in categories
 join prod in products on category.ID equals prod.CategoryID
 into prodGroup
 select new { CategoryName = category.Name, Products = prodGroup };

左外部連接

var leftOuterJoinQuery =
             from category in categories
             join prod in products on category.ID equals prod.CategoryID
             into prodGroup
                     from item in prodGroup.DefaultIfEmpty(new Product{Name =
             string.Empty, CategoryID = 0})
                     select new { CatName = category.Name, ProdName = item.Name };

分析:

在左外連接中,將返回左側源序列中的所有元素,即使它們在右側序列中沒有匹配的元素也是如此。
若要在Linq中執(zhí)行左外連接,請將DefaultIfEmpty方法與分組連接結合起來,以指定要在某個元素不具有匹配元素時產(chǎn)生的默認右側元素,可以使用null作為任何引用類型的默認值。也可以指定用戶定義的默認類型。

UNION子句

一、簡介

Union返回并集,并集是指位于兩個集合中任一集合的唯一的元素(自動去重復了)。在LINQ中UNION默認是去重的,沒有UNION ALL 語句,不去重用CONCAT()。

二、案例

1.查詢語句寫法

Union會去除重復項,相當于SQL的Union

var q = (from c in db.Customers
         select c.Country
           ).Union(from e in db.Employees
                   select e.Country
           );

相當于

var q1 = from s in db.Student
                        where s.ID < 3
                        select s;
var q2 = from s in db.Student
                        where s.ID < 5
                        select s;

 //去掉重復的
var q = q1.Union(q2);
var r = q.ToList();//ToList之后,會把數(shù)據(jù)查出來在內(nèi)存中操作

如果不去重,用Concat()

//Concat不會去除重復項目,相當于SQL的Union All;
//不去掉重復的 相當于union all,
var q3 = q1.Concat(q2);
var r3 = q3.ToList()

2.另一種寫法

var q = db.Customers.Union(db.Employees).select(d=>d.Country);

原文鏈接:https://www.cnblogs.com/wml-it/p/14837159.html

欄目分類
最近更新