Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq编码风格:内联if_C#_Sql_Linq - Fatal编程技术网

C# Linq编码风格:内联if

C# Linq编码风格:内联if,c#,sql,linq,C#,Sql,Linq,我有一个关于编写linq查询的常见做法的问题。事实上我和我的同事吵了一架 我们有一个布尔变量,以防它为真-需要额外的检查。如果是假的,就不应该有这样的支票 在linq中有两种实现方法: bool onlyForReturningCustomers; ..... return context.Products.Where(product => product.StartTime >= fromDate &

我有一个关于编写linq查询的常见做法的问题。事实上我和我的同事吵了一架

我们有一个布尔变量,以防它为真-需要额外的检查。如果是假的,就不应该有这样的支票

在linq中有两种实现方法:

bool onlyForReturningCustomers;    
.....    
return context.Products.Where(product => product.StartTime >= fromDate 
                                && product.StartTime < toDate 
                                && (onlyForReturningCustomers ? product.IsReturningClient : true));
bool仅适用于客户;
.....    
返回context.Products.Where(product=>product.StartTime>=fromDate
&&product.StartTime
第二点:

bool onlyForReturningCustomers;
.....            
var q = context.Products.Where(product => product.StartTime >= fromDate && product.StartTime < toDate);

if (onlyForReturningCustomers) {
  q = q.Where(product => product.IsReturningClient);
}
return q;
bool仅适用于客户;
.....            
var q=context.Products.Where(product=>product.StartTime>=fromDate&&product.StartTimeproduct.IsReturningClient);
}
返回q;
第一个是在sql中呈现
case
语句,当
onlyForReturningCustomers=false
时,会出现类似
1=1
的语句,但这段代码更容易阅读

第二个不是那么容易阅读,但它在sql中呈现清晰的语句,没有任何垃圾

你会用哪一种?

我可能会选择

bool onlyForReturningCustomers;
.....            
// Make a positively-named variable
bool includeAllCustomers = !onlyForReturningCustomers;
var q = context.Products.Where(product => product.StartTime >= fromDate 
                                       && product.StartTime < toDate
                                       && (includeAllCustomers 
                                           || product.IsReturningClient));

return q;
bool仅适用于客户;
.....            
//生成一个正名的变量
bool includealcustomers=!仅限于令人担忧的客户;
var q=context.Products.Where(product=>product.StartTime>=fromDate
&&product.StartTime

这基本上与第一种方法相同,但没有条件表达式的奇怪之处,其中一个分支只说
true

我会使用第一种方法,因为第二种方法看起来实际上是两次往返数据


我还将复制LINQ语句发出的SQL,将其粘贴到您最喜欢的SQL工具(例如SQL Server Management Studio),在
SELECT
语句上方添加
SET STATISTICS IO,并检查执行查询所需的逻辑读取(越低越好)。

第二条语句越容易阅读,而且,如果您将来为退货客户或其他类型的客户添加了业务规则,那么维护起来也更容易。

您似乎已经具备了回答这个问题的工具/知识。为什么不直接执行(!onlyForReturningCustomers | | product.IsReturningClient)?使用变量保存:)@mattytomo作为一种风格,我更喜欢布尔条件被积极地表达/使用,我相信这有助于理解。我认为在代码中有一些东西是完整的(对不起,现在没有)啊,很公平,我同意:)+1对于您的回答,它不应该需要两次往返:LINQ查询通常会推迟到您实际请求结果时。