条件逻辑与linq查询语法

本文关键字:语法 查询 linq 条件逻辑 | 更新日期: 2023-09-27 17:54:48

我有下面的条件,它执行两个查询中的一个,这两个查询只不同于附加子句

&& acc.Fb_DataSourceKey == dskId

这是条件句

var statData = dskId != -1 ? from s in dao.fb_statdata
                            join acc in dao.fb_datasourceadaccount
                            on s.Fb_DataSourceAdAccountId equals acc.Id
                            where s.ReportTypeId == 1
                            && acc.Fb_DataSourceKey == dskId
                            group new { s, acc.Fb_DataSourceKey }  by new { s.Fb_DataSourceAdAccountId, s.Start_time } into res
                            select res
                            :               
                            from s in dao.fb_statdata
                            join acc in dao.fb_datasourceadaccount
                            on s.Fb_DataSourceAdAccountId equals acc.Id
                            where s.ReportTypeId == 1
                            group new { s, acc.Fb_DataSourceKey }  by new { s.Fb_DataSourceAdAccountId, s.Start_time } into res
                            select res;

现在,多亏了https://stackoverflow.com/a/2850048/1170932,我知道我可以把它改成下面的

            var statData = from s in dao.fb_statdata
                            join acc in dao.fb_datasourceadaccount
                            on s.Fb_DataSourceAdAccountId equals acc.Id
                            where s.ReportTypeId == 1
                            group new { s, acc.Fb_DataSourceKey } by new { s.Fb_DataSourceAdAccountId, s.Start_time } into res
                            select res;
            if (singleDsk)
                statData = from s in statData where s.Key.Fb_DataSourceAdAccountId == dskId select s;

这消除了代码重复,但导致使用效率极低的外连接(实际上可以理解)。我们使用MySQL作为我们的数据库。

外连接的速度慢得令人无法接受。是否有一种方法可以在不生成外部连接和不复制代码的情况下执行查询样式条件?

条件逻辑与linq查询语法

在连接之前使用过滤器,而不是在连接之后。

var accounts = dao.fb_datasourceadaccount.AsQueryable();
if(dskId != -1)
    accounts = accounts.Where(acc => acc.Fb_DataSourceKey == dskId);
var statData = from s in dao.fb_statdata
                join acc in accounts
                on s.Fb_DataSourceAdAccountId equals acc.Id
                where s.ReportTypeId == 1
                group new { s, acc.Fb_DataSourceKey } 
                by new { s.Fb_DataSourceAdAccountId, s.Start_time } 
                into res
                select res;