简体   繁体   English

如何在LINQ to SQL中使用或运算符

[英]How to use or operator in linq to sql

I am using this code but getting an error. 我正在使用此代码,但出现错误。 I want to use an OR operator. 我想使用OR运算符。

DataClasses1DataContext dc = new DataClasses1DataContext();

private void button4_Click(object sender, EventArgs e)
{
   var i = dc.vins
             .Where(aa => aa.startDate < DateTime.Now)
             .Where(aa => aa.Sno > 1)
             .Select(aa => aa);
   dataGridView1.DataSource = i;
}

This code is working as an "AND" operator how can I have it act as an "OR" operator? 该代码用作"AND"运算符,如何使其充当"OR"运算符?

Just put both conditions in one Where call, and use the normal C# || 只需将两个条件放在一个Where调用中,并使用普通的C# || operator: 操作员:

var i = dc.vins.Where(aa => aa.startDate < DateTime.Now || aa.Sno > 1);

Note that I've also removed your Select call as it wasn't doing anything useful. 请注意,我也删除了您的Select调用,因为它没有做任何有用的事情。

Note that depending on your exact scenario, you may well want to use DateTime.UtcNow instead of DateTime.Now ; 请注意,根据您的实际情况,您可能希望使用DateTime.UtcNow而不是DateTime.Now ; you should carefully consider how you want time zones to be handled. 您应该仔细考虑如何处理时区。

how about this? 这个怎么样?

var i = dc.vins.Where(aa => (aa.startDate < DateTime.Now) || (aa.Sno > 1));

and actually your AND condition should look like this, 实际上,您的AND条件应如下所示,

var i = dc.vins.Where(aa => (aa.startDate < DateTime.Now) && (aa.Sno > 1));

.Select() is optional since you have not done any calculation or modification on aa . .Select()是可选的,因为您尚未对aa进行任何计算或修改。

采用

.Where(aa => aa.startDate < DateTime.Now || aa.Sno > 1 ).Select...

Simply use the || 只需使用|| inside your WHERE clause 在您的WHERE子句中

var i = dc.vins.Where(aa => aa.startDate < DateTime.Now || aa.Sno > 1);

The OR operator is || OR运算符为|| , therefore you can try: ,因此您可以尝试:

var i = dc.vins.Where(aa => aa.startDate < DateTime.Now || aa.Sno > 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM