The problem with your question is that from what you say, the code should work. For example, the following code works correctly:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
class Test
{
public string Time;
}
class Program
{
static void Main()
{
var Model = new List<Test>
{
new Test{Time = "01:01:01"},
// null, // Uncomment this line to make it crash.
new Test{Time = null},
new Test{Time = "02:02:02"}
};
int result = Model.Sum(x => TimeSpan.Parse(x.Time ?? "00:00:00").Minutes);
Console.WriteLine(result);
}
}
}
Since you say an error is occurring, there must be something else going wrong. I think that the issue is that x
itself is null.
We can demonstrate that possibility by uncommenting the indicated line. If you do that, the program will crash.
If that is indeed the problem, then the solution is very simple; just change the summation to:
int result = Model.Sum(x => TimeSpan.Parse(x?.Time ?? "00:00:00").Minutes);
After making that change, a null x
will not make it crash.
Note that it may be slightly better to write:
int result = Model.Sum(x => x?.Time != null ? TimeSpan.Parse(x.Time).Minutes : 0 );
because then you avoid parsing "00:00:00"
only to return zero (via .Minutes
), but the difference is likely to be very marginal if any.