如何通过linq到sql中的子查询检查记录是否存在于组中

时间:2015-04-20 13:42:46

标签: c# sql sql-server linq linq-to-sql

我想通过Linq中的记录获取组中存在哪些记录的结果。 我在SQL中获得了查询,但我很难在LINQ中获取它

在SQL查询中

 select LEVEL, DESCR
   from ACTIVITY_LKUP 
   WHERE LEVEL IN ( //Checking row exists
    select TOP 2 b.LEVEL
    from ACTIVITY_LKUP b
    WHERE b.LEVEL > (
    select max(b.LEVEL)
    from ACTIVITY a, ACTIVITY_LKUP b
    WHERE b.TYPE = a.ACTIVITY_TYPE
    and a.JOB_CANDIDATE_ID = 1
   )
  group by b.level //Grouping here
  )
order by LEVEL 

在Linq查询中

 var duplicate =(from lkup in ACTIVITY_LKUP
                where lkup.LEVEL== (from actlk in ACTIVITY_LKUP //Iam Not able to check row exists in  the group by
                where actlk.LEVEL >
                (
                 from act in ACTIVITY
                 join lkup in ACTIVITY_LKUP on act.ACTIVITY_TYPE equals lkup.TYPE
                 where act.JOB_CANDIDATE_ID == 1
                 orderby lkup.LEVEL
                 select lkup.LEVEL
                 ).First()            
                group actlk by actlk.LEVEL into lggrp
                select new { LEVEL = lggrp.Key,DESCR=lggrp.Select(x=>x.DESCR)              
              }).Take(2)
             select lkup)

显示错误行"运营商' =='不能应用于' int?'类型的操作数。和' System.Linq.IQueryable"。

我们怎么能在LINQ中做到这一点?帮帮我。

2 个答案:

答案 0 :(得分:0)

您还可以尝试在查询中加入相等的列,例如

var duplicate=(from lg in reslandentity.ACTIVITY_LKUP
               join grp in
                  (from actlk in reslandentity.ACTIVITY_LKUP
                    where actlk.LEVEL >
                     (
                       from act in reslandentity.ACTIVITY
                       join lkup in reslandentity.ACTIVITY_LKUP on act.ACTIVITY_TYPE equals lkup.TYPE
                       where act.JOB_CANDIDATE_ID == 1
                       orderby lkup.LEVEL
                       select lkup.LEVEL
                     ).FirstOrDefault()
                      orderby actlk.LEVEL
                      group actlk by actlk.LEVEL into lggrp
                      select new { LEVEL = lggrp.Key }).Take(2) 
                 on lg.LEVEL equals grp.LEVEL
                 select lg).ToList();

希望它可以帮助你...... !!

答案 1 :(得分:-1)

我认为您需要在查询中添加字段类型。您可以尝试这样的查询。

var duplicate= from myRow in dt.AsEnumerable()
               where myRow.Field<DateTime>("Con_Date").Date <= StartDate && myRow.Field<DateTime>("Con_Date").Date >= EndDate
                          select myRow;