LINQ TO SQL 的几种用法

一、Union  返回并集,并集是指位于两个集合中任一集合的唯一的元素(自动去重复了)。

Union会去除重复项,相当于SQL的Union

1.查询语句写法
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之后,会把数据查出来在内存中操作

                 //linq里面 没有union all的写法

                 //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);
 

二、Intersect 返回交集,交集是指同时出现在两个集合中的元素。

var q =  (from c in db.Customers            
          select c.Age         
         ).Intersect(             
                    from e in db.Employees             
                    select e.Age
         );

三、Except 返回差集,差集是指位于一个集合但不位于另一个集合的元素。

       Except 是把第一个集合里面的数据 去掉在第二个集合里面出现过的数据。

var q = (from c in db.Customers    
select c.Name ).Except(from e in db.Employees
select e.Name );
               //1 2 这两条记录

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

               //1 2 3 4 这四条记录

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

               var r = q1.Except(q2).ToList();

               var r2 = q2.Except(q1).ToList();

四、Distinct 返回的序列包含输入序列的唯一元素。

       该方法是单个集合操作

List<int> list = new List<int>() {1,2,3,3,3};
var result = list.Distinct();

    result 的值为  {1,2,3}

posted @ 2020-12-30 15:25  清和时光  阅读(438)  评论(0编辑  收藏  举报