Home > Mobile >  How to handle "Nullable value type may be null" (for TimeSpan) inside the sum() methode?
How to handle "Nullable value type may be null" (for TimeSpan) inside the sum() methode?

Time:10-26

In my Asp.net core project, I need to check for null TimeSpan properties. This is my method:

 return result.Include(e => e.Episodes).AsEnumerable().Select(c => new ShowListCoursesViewModel()
            {
                CourseId = c.CourseId,
                CourseImageName = c.CourseImageName,
                CoursePrice = Convert.ToDecimal(c.CoursePrice),
                CourseTitle = c.CopurseTitle,
                CourseTotalTime = new TimeSpan(c.Episodes.Sum(t => t.EpisodeTimeLength.Value.Ticks) )
            }).Skip(skip).Take(take).OrderByDescending(d => d.CoursePrice).ToList();

It's showing a green squiggle under the t.EpisodeTimeLength and saying:

Nullable value type may be null.

My CourseTotalTime property is nullable and also the EpisodeTimeLength is nullable too.

How can I interpret null values of EpisodeTimeLength as 00:00:00 in the Sum? Example: [null, 01:00:00, 01:00:00] should yield 02:00:00 in CourseTotaltime.

CodePudding user response:

You can exclude null values with Where before the Sum:

CourseTotalTime = new TimeSpan(
    c.Episodes
        .Where(t => t.EpisodeTimeLength.HasValue)
        .Sum(t => t.EpisodeTimeLength.Value.Ticks))

Alternatively, you can specify a default value to use when t.EpisodeTimeLength is null:

CourseTotalTime = new TimeSpan(
    c.Episodes
        .Sum(t => (t.EpisodeTimeLength ?? TimeSpan.Zero).Ticks))

This makes use of the null-coalescing operator.

Demonstration of both approaches

  • Related