动态添加连接到linq查询的技术?

时间:2012-12-21 18:17:15

标签: linq entity-framework

我有一个Linq查询,有时会连接两个数据集,有时连接三个。永远不会从第三组返回数据,它仅用于根据数据内容过滤数据。我使用Predicate Builder动态创建轮廓,但不确定动态包含/排除连接数据集的正确方法。

有时这个:

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

有时我需要这个:

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

是否有最佳做法或技巧? TIA

1 个答案:

答案 0 :(得分:3)

对于性能,我会在if语句中添加额外的连接。这将在两种情况下构建一个有效的查询:

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

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

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可能会优化生成的查询,但您应该检查以确定。