简体   繁体   中英

C# LINQ How to efficiently deal with a null return?

So when I'm writing C# linq statements I often would like to do something like this:

string name = database.table.Where(t=>t.Field1 == row.Field1 && t.Field2 == row.Field).Select(b=> b.Name).FirstOrDefault().ToString();

However if the statement above doesn't return anything then it errors because you can't use.FirstOrDefault() on a null value.

So what I usually end up doing instead is something like below:

var listOfNames = database.table.Where(t=>t.Field1 == row.Field1 && t.Field2 == row.Field).Select(b=> b.Name).ToList();
  
if(listOfNames.Count() > 0 ){
  string name =  listOfNames.FirstOrDefault().ToString();
}

The code above just seems really verbose and I have to imagine there is a much cleaner way of doing this while dealing with a potential null return value.

Any insight or help would be appreciated. Thanks.

You have a few ways:

  1. do not use ToString() I guess Name is string/varchar already
string name = database.table
  .Where(t=>t.Field1 == row.Field1 && t.Field2 == row.Field)
  .Select(b=> b.Name)
  .FirstOrDefault()
// name now can be null since default(string) is null
  1. if you need to do ToString then you can use C# 6 features – Null-conditional (?.)
string name = database.table
  .Where(t=>t.Field1 == row.Field1 && t.Field2 == row.Field)
  .Select(b=> b.Name)
  .FirstOrDefault()?.ToString(); // here ?
// name now can be null
  1. also consider null-coalescing (??) operator
string name = database.table
  .Where(t=>t.Field1 == row.Field1 && t.Field2 == row.Field)
  .Select(b=> b.Name)
  .FirstOrDefault() ?? "some value"
// so if FirstOrDefault returns null then "some value" will be used

Combine the .Where and .FirstOrDefault :

string name = database.table
  .FirstOrDefault(t=>t.Field1 == row.Field1 && t.Field2 == row.Field)
  ?.Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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