动态添加连接到linq查询的技术? [英] Technique for dynamically adding a join to a linq query?

查看:85
本文介绍了动态添加连接到linq查询的技术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Linq查询,有时连接在两个数据集上,其他的时候连接在三个。没有从第三集返回的数据,它仅用于根据内容过滤数据。我使用Predicate Builder动态创建,但不确定动态地包含/排除连接的数据集的正确方法。



有时这个:

  var filteredResults = from d in dateRangeResults 
在d.ID结果中加入n,等于n.ID
select new {name = n,demo = d};

其他时候我需要这样:

  var filteredResults = from d in dateRangeResults 
在d.ID的结果中连接n等于n.ID
在pnSIncludeResults中连接p,n.ID等于p
选择新的{name = n,demo = d};

有最好的做法还是技术?
TIA

解决方案

对于演出,我将在中添加额外的加入,如果语句。这将在两种情况下构建一个单一的高效查询:

  var filteredResults = from d in dateRangeResults 
在结果中连接n在d.ID等于n.ID
select new {name = n,demo = d};

如果(filterExtra)
{
filteredResults =来自resultResult的结果
在pnSIncludeResults中加入p,result.name.ID等于p
select result;
}

如果您更关心可读性,可以使用 where clause而不是 join 子句:

 code> var filteredResults = from d in dateRangeResults 
在d.ID结果中连接n等于n.ID
其中!filterExtra || PnSIncludeResults.Contains(n.ID)
select new {name = n,demo = d};

LINQ to Entities可能优化结果查询,但您应该检查一下。


I have a Linq query that sometimes is joined on two datasets and at other times is joined on three. There is never data returned from the third set it is just used to filter the data based on it's content. I use Predicate Builder for dynamically creating wheres but am not sure the right way to dynamically include/exclude a joined dataset.

Sometimes this:

var filteredResults = from d in dateRangeResults
                              join n in results on d.ID equals n.ID                                
                              select new { name = n, demo = d };

And other times I need this:

    var filteredResults = from d in dateRangeResults
                              join n in results on d.ID equals n.ID
                              join p in PnSIncludeResults on n.ID equals p
                              select new { name = n, demo = d };

Is there a best practice or technique? TIA

解决方案

For performance I would add the extra join within an if statement. This will build a single efficient query in both cases:

var filteredResults = from d in dateRangeResults
                      join n in results on d.ID equals n.ID
                      select new { name = n, demo = d };

if(filterExtra)
{
    filteredResults = from result in filteredResults
                      join p in PnSIncludeResults on result.name.ID equals p
                      select result;
}

If you're more concerned about readability, you can use a where clause instead of a join clause:

var filteredResults = from d in dateRangeResults
                      join n in results on d.ID equals n.ID
                      where !filterExtra || PnSIncludeResults.Contains(n.ID)
                      select new { name = n, demo = d };

LINQ to Entities might optimize the resulting query, but you should check to be sure.

这篇关于动态添加连接到linq查询的技术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆