C# 检查 LINQ 查询中的 Var 是否为 Null 并返回早于 x 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1150096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:25:54  来源:igfitidea点击:

Checking if Var from LINQ query is Null and returning values older than x

c#linqdatetimeerror-handling

提问by manemawanna

Hello everyone I'm currently having 2 issues with the code below:

大家好,我目前在使用以下代码时遇到了两个问题:

  1. Upon return of result1 I'm trying to complete a check to see if it is != null and if it is't it will begin to delete the records selected. The issue is that even when result1 returns nothing and defaults the if statement doesn't pick this up so I guess I'm missing something but what?

  2. I'm wishing to return only values which are over 10 mintues old (this will later be scaled to 12 hours) to do this I'm checking against a.DateTime which is a DateTime value stored in a database. However if i use the <= or >= operators it doesn't work so again what am I missing?

    DateTime dateTime = DateTime.Now.Subtract(new TimeSpan(0, 0, 10, 0));
    
    var result1 = (from a in cpuInfo
                      where a.DateTime <= dateTime
                      select a).DefaultIfEmpty(null);
    
    if (result1 != null)
    {            
        foreach (TblCPUInfo record1 in result1)
        {
                localDB.TblCPUInfo.DeleteOnSubmit(record1);
                localDB.SubmitChanges();
        }
    }
    
  1. 返回 result1 后,我正在尝试完成检查以查看它是否为 != null,如果不是,它将开始删除选定的记录。问题是,即使 result1 不返回任何内容并默认,if 语句也不会选择它,所以我想我错过了一些东西,但是什么?

  2. 我希望只返回超过 10 分钟的值(稍后将缩放到 12 小时)来执行此操作我正在检查 a.DateTime,它是存储在数据库中的 DateTime 值。但是,如果我使用 <= 或 >= 运算符,它不起作用,那么我又错过了什么?

    DateTime dateTime = DateTime.Now.Subtract(new TimeSpan(0, 0, 10, 0));
    
    var result1 = (from a in cpuInfo
                      where a.DateTime <= dateTime
                      select a).DefaultIfEmpty(null);
    
    if (result1 != null)
    {            
        foreach (TblCPUInfo record1 in result1)
        {
                localDB.TblCPUInfo.DeleteOnSubmit(record1);
                localDB.SubmitChanges();
        }
    }
    

采纳答案by Jon Skeet

Philippe has talked about the sequence side of things - although you don't even need the call to Any(). After all, if there are no changes the loop just won't do anything.

Philippe 已经谈到了事物的序列方面 - 尽管您甚至不需要调用Any(). 毕竟,如果没有变化,循环就不会做任何事情。

Do you really want to submit the changes on each iteration? It would probably make more sense to do this once at the end. Additionally, you can use DateTime.AddMinutesto make the initial "10 minutes ago" simpler, and if you're only filtering by a Whereclause I'd use dot notation.

您真的想在每次迭代时提交更改吗?最后这样做一次可能更有意义。此外,您可以使用DateTime.AddMinutes使初始的“10 分钟前”更简单,如果您仅按Where子句进行过滤,我将使用点表示法。

After all these changes (and making the variable names more useful), the code would look like this:

在所有这些更改(并使变量名更有用)之后,代码将如下所示:

DateTime tenMinutesAgo = DateTime.Now.AddMinutes(-10);

var entriesToDelete = cpuInfo.Where(entry => entry.DateTime <= tenMinutesAgo);

foreach (var entry in entriesToDelete)
{
    localDB.TblCPUInfo.DeleteOnSubmit(entry);
}
localDB.SubmitChanges();

Now, as for why <= isn't working for you... is it possible that you need the UTC time instead of the local time? For example:

现在,至于为什么 <= 对您不起作用……您是否可能需要 UTC 时间而不是当地时间?例如:

DateTime tenMinutesAgo = DateTime.UtcNow.AddMinutes(-10);

If that still isn't working, I suggest you have a look at the generated query and play with it in a SQL tool (e.g. Enterprise Manager or SQL Server Management Studio) to work out why it's not returning any results.

如果这仍然不起作用,我建议您查看生成的查询并在 SQL 工具(例如企业管理器或 SQL Server Management Studio)中使用它以找出它不返回任何结果的原因。

回答by Philippe Leybaert

DefaultIfEmpty will return a single item with the content you provided, so in your case a collection with a single value "null".

DefaultIfEmpty 将返回具有您提供的内容的单个项目,因此在您的情况下是具有单个值“null”的集合。

You should check for elements in the collection using the Any() extension method. In your case:

您应该使用 Any() 扩展方法检查集合中的元素。在你的情况下:

DateTime dateTime = DateTime.Now.Subtract(new TimeSpan(0, 0, 10, 0));

var result1 = from a in cpuInfo
                  where a.DateTime <= dateTime
                  select a;

if (result1.Any())
{            
    foreach (TblCPUInfo record1 in result1)
    {
            localDB.TblCPUInfo.DeleteOnSubmit(record1);
            localDB.SubmitChanges();
    }
}

But if this is really your code, you can skip the Any() check completely, because the foreach loop will not run if there are no elements in result1.

但是如果这真的是你的代码,你可以完全跳过 Any() 检查,因为如果 result1 中没有元素,foreach 循环将不会运行。