[英]Linq most efficient method
I have need to use Linq statement as following 我需要使用Linq语句如下
var data = db.tbl1
.Where(w => clientIds == clientid && w.Source == source);
I have a dropdown where I am getting source from. 我有一个下拉列表,我从中得到消息来源。 The dropdown values are as such:
下拉值如下:
All
NewsPaper
Web
The thing is NewsPaper and Web are valid values for Source. 事情是NewsPaper和Web是Source的有效值。 All is not.
一切都不是。 All means that a record can be NewsPaper or Web.
所有意味着记录可以是NewsPaper或Web。
If they choose All, how do I modify w.Source such that All means NewsPaper or Web. 如果他们选择All,我如何修改w.Source,以便All表示NewsPaper或Web。 I can do 2 seperate queries as shown below but rather not:
我可以执行2个单独的查询,如下所示,但不是:
if(source == "All")
{
var data = db.tbl1
.Where(w => clientIds == clientid);
}
else
{
var data = db.tbl1
.Where(w => clientIds == clientid && w.Source == source);
}
I like to do it in 1 query as the query I have is actually more complicated than what is shown above. 我喜欢在1个查询中执行它,因为我的查询实际上比上面显示的更复杂。
Thank you in advance 先感谢您
Try this: 尝试这个:
var data = db.tbl1
.Where(w => clientIds == clientid && (source == "All" || w.Source == source));
@mattytommo answer is acceptable, but I prefer to break them out a bit. @mattytommo答案是可以接受的,但我更喜欢将它们分解出来。 IMO a little more readable.
IMO更具可读性。
var data = db.tbl1.Where(w => clientIds == clientid);
if (source != "All")
data = data.Where(w => w.Source == source);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.