Linq To Sql中实现Left Join与Inner Join使用Linq语法与lambda表达式

当前有两个表,sgroup与sgroupuser,两者通过gKey关联,而sgroup表记录的是组,而sgroupuser记录是组中的用户,因此在sgroupuser中不一定有数据。需要使用Left Join获取数据:

Linq语法如下:

var sg = (from g in dc.sgroup
                     join gu in dc.sgroupuser on g.gKey equals gu.gKey into l
                     from lgu in l.DefaultIfEmpty()
                      select new { g, lgu }).ToList();

Lambda表达式如下:

var sg = dc.sgroup.GroupJoin(dc.sgroupuser, g => g.gKey, gu => gu.gKey, (g, gu) => new { g, gu }).Select(o=>o).ToList() ;

注意:

Linq 与Lambda表达式取出的结果有所不同.Linq取出的结果的记录数与Sql中的Left Join的结果相同,而Lambda表达式取出的记录数是sgroup表中的记录数,sgroupuser对应的记录是以对象集合存在于结果中

附:

下面是Inner Join:

Linq语法如下:

var sg = (from g in dc.sgroup
                    join gu in dc.sgroupuser on g.gKey equals gu.gKey                  
                    select new { g, gu }).ToList();

Lambda表达式如下:

var sg = dc.sgroup.Join(dc.sgroupuser, g => g.gKey, gu => gu.gKey, (g, gu) => new { g, gu }).Select(o=>o).ToList() ;

注意:

上面最后都用到了ToList()方法 , 用ToList()是为了一次性将数据取到本地.

        private string GetSecSolicitImplementCount(DataSet aTmpDs1, DataSet aTmpDs2, int aMonth)
{
DataTable dt1 = aTmpDs1.Tables[];
DataTable dt2 = aTmpDs2.Tables[]; //使用LINQ计算二次招揽任务实施数
var query = from row1 in dt1.AsEnumerable()
join row2 in dt2.AsEnumerable() on row1.Field<string>("TASKID") equals row2.Field<string>("TASKID")
into l
from lgu in l.DefaultIfEmpty()
where row1.Field<DateTime>("NEXTSTEPTIME1").Month == aMonth &&
(lgu == null ||
row1.Field<DateTime>("NEXTSTEPTIME1") <= lgu.Field<DateTime>("DELIVEREDDATE") )
select new
{
TaskID = row1.Field<string>("TASKID"),
lgu
}; var secSolicitImplementCount = query.ToArray().Count(); return secSolicitImplementCount.ToString(); }
上一篇:js去除字符串空格(空白符)


下一篇:mysql5.7版本yum安装---redhat7.0