Linq使用'not exists'和'group by'对象?

时间:2012-04-10 13:33:05

标签: c# linq fluent-nhibernate

我已经分配了一个使用NHibernate的新项目。我可以在sql中轻松编写的查询让我完全难以理解如何在linq中执行此操作,这就是我被告知要执行此操作的方式。

所以,这是查询:

select  ts.BatchID, COUNT(distinct ts.UniqID) SurveyCount
from    TeleformStaging.TeleformStaging ts
where   ts.IsRescan = 0
and     not exists (select  bfr.BatchID
                    from    TeleformStaging.BatchesForRescan bfr
                    where   bfr.BatchTrack = ts.BatchID)
group by ts.BatchID
order by ts.BatchID

我相信我可以得到'分组'部分,但不知道子查询。

感谢您的任何建议......

3 个答案:

答案 0 :(得分:5)

也许是这样的:

var result= (
        from ts in db.TeleformStaging
        where ts.IsRescan == false //if is a boolean else == 0
        && 
        !(
            from bfr in db.BatchesForRescan
            select bfr.BatchTrack
        ).Contains(ts.BatchID)
        orderby ts.BatchID
        group ts by ts.BatchID into g
        select new
        {
            BatchID=g.Key,
            SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
        }
    );

其中db是linq数据上下文

修改

您也可以使用.Any()执行此操作。像这样:

var result= (
        from ts in db.TeleformStaging
        where ts.IsRescan == false //if is a boolean else == 0
        && 
        !(
            from bfr in db.BatchesForRescan
            where ts.BatchID==bfr.BatchTrack
            select bfr.BatchTrack
        ).Any()
        orderby ts.BatchID
        group ts by ts.BatchID into g
        select new
        {
            BatchID=g.Key,
            SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
        }
    );

修改1

有用的链接:

答案 1 :(得分:0)

from fs in context.TeleformStaging
where !ts.IsRescan && !context.BatchesForRescan.Any(bfr=>bfr.BatchTrack == ts.BatchID)
group ts by ts.BatchID into g
    select new
    {
        BatchID=g.Key,
        SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
    }

with group by

答案 2 :(得分:0)

LINQ略有颠倒,但确实提供了一些lambda表达式的复杂性;这看起来如何:

var result = from ts in TeleformStaging.TeleformStaging
                where !ts.IsRescan && !TeleformStaging.BatchesForRescan.Any(bfr => bfr.BatchID == ts.BatchID)
                group ts by ts.BatchID into tsGrouped
                orderby tsGrouped.Key
                select new
                {
                    BatchId = tsGrouped.Key,
                    SurveyCount = tsGrouped.Select(x => x.UniqID).Distinct().Count()
                };