带有linq查询语法的条件逻辑

时间:2014-03-28 17:59:59

标签: c# linq linq-query-syntax

我有以下条件,它执行两个查询中的一个,这些查询完全不同于附加条款

&& 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;

这消除了代码重复,但导致使用非常低效的外连接(可以理解,真的)。 FTR我们正在为我们的数据库使用MySQL。

不幸的是,外连接速度慢得令人无法接受。有没有办法在没有生成外连接且没有重复代码的情况下执行查询样式条件?

1 个答案:

答案 0 :(得分:1)

在之前进行过滤器,而不是之后。

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;