Home > Enterprise >  Check for null before continuing linq and return value as "-"
Check for null before continuing linq and return value as "-"

Time:10-25

I have this code. Using Visual Studio

DisplayTimeStamp = PredictionTableList
.Where(x => x.ContextTimestamp != null)
.Select(x => x.ContextTimestamp)
.FirstOrDefault();

It checks the first data of the table. The thing is sometimes "PredictionTableList" is null. How do I check for this and return the null value as "-"?

CodePudding user response:

Option 1: An if-else statement to check whether PredictionTableList is null.

if (PredictionTableList == null)
    DisplayTimeStamp = "-";
else
    DisplayTimeStamp = PredictionTableList.Where(x => x.ContextTimestamp != null)
        .Select(x => x.ContextTimestamp)
        .FirstOrDefault();

Option 2: Ternary operator

DisplayTimeStamp = PredictionTableList == null
    ? "-"
    : PredictionTableList.Where(x => x.ContextTimestamp != null)
        .Select(x => x.ContextTimestamp)
        .FirstOrDefault();

CodePudding user response:

If you are using .NET >= version 5, use the ? operator like that:

DisplayTimeStamp = PredictionTableList?
    .Where(x => x.ContextTimestamp != null)?
    .Select(x => x.ContextTimestamp)?
    .FirstOrDefault();

If PredictionTableList is null DisplayTimeStamp will be null. No other code will be executed.

CodePudding user response:

Something like this:

DisplayTimeStamp = PredictionTableList?.Where(x => x.ContextTimestamp != null) .Select(x => x.ContextTimestamp).FirstOrDefault() ?? "-";

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-

CodePudding user response:

Another option: combining the ? and ?? operators:

DisplayTimeStamp = PredictionTableList?
.Where(x => x.ContextTimestamp != null)
.Select(x => x.ContextTimestamp)
.FirstOrDefault() ?? "-";
  • Related