动态添加连接到linq查询的技术? [英] Technique for dynamically adding a join to a linq query?
问题描述
有时这个:
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屋!