简体   繁体   English

用linq比较无值

[英]compare none value by linq

I have an integer column(not null) in a sql server 2008 database/table, I want to retrieve it. 我在sql server 2008数据库/表中有一个整数列(不为null),我想检索它。

  // go to the table and get the largest number, if none exists, use 0.
        int iNumber = iContext.DetailsRecords.Max(x => x.Number); // from entity

But at the very beginning, the table is empty. 但在一开始,该表是空的。 I want to set is as 0. How to change the code? 我要设置为0。如何更改代码?

If you don't want to check if the DetailsRecords is null, but rather handle if the source sequence is empty, then use this answer (I adjusted it a bit differently for your LINQ usage): 如果您不想检查DetailsRecords是否为空,而是要检查源序列是否为空,请使用此答案(我对您的LINQ用法进行了一些不同的调整):

Max or Default? 最高还是默认?


int iNumber = iContext.DetailsRecords.Select(x => (int?)x.Number).Max() ?? 0;

try this: 尝试这个:
int iNumber = iContext.DetailsRecords==null? iContext.DetailsRecords.Max(x => x.Number) : 0;
or 要么
int iNumber = iContext.DetailsRecords.Any()? iContext.DetailsRecords.Max(x => x.Number) : 0; if table is not null and contains 0 records. 如果table不为null,并且包含0条记录。

You can use DefaultIfEmpty for this. 您可以为此使用DefaultIfEmpty If the sequence is empty it will return the provided item as the only item in the sequence, if not it will return the original sequence. 如果序列为空,则将提供的项目作为序列中的唯一项目返回;否则,将返回原始序列。

IEnumerable<int> numbers = new int [] { };

numbers.DefaultIfEmpty(0).Max();

Use the Any function to see if there are any records: 使用“ Any功能查看是否有任何记录:

int iNumber = iContext.DetailsRecords.Any() 
              ? iContext.DetailsRecords.Max(x => x.Number) 
              : 0;

I know this already has an accepted answer, but another good way would just be FirstOrDefault(). 我知道这已经有了一个可以接受的答案,但是另一个好方法就是FirstOrDefault()。

int iNumber = iContext.DetailsRecords.OrderByDescending(x => x.Number).FirstOrDefault();

I use this way often and also can let you setup a new object if the result was null. 我经常使用这种方式,如果结果为null,也可以让您设置一个新对象。

 MyObject m = mySearch.GetItems.Where(a => a.id == id).FirstOrDefault() ?? new MyObject();

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

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