Search code examples
c#.netlinq

Check for null before continuing LINQ and return value as "-"


I have this code.

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

It returns the first data of the table. Sometimes PredictionTableList is null, how do I check for this and return the null value as "-"?


Solution

  • 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();