-2

Here is the LINQ query that I have:

 var t2 = t1.GroupBy(x => x.DateYYMMDD)
            .OrderBy(g => g.Key)
            .Select(g => new ScreenTimeModel
            {
                 DateYYMMDD = $"20{g.Key.Substring(0, 2)}/{g.Key.Substring(2, 2)}/{g.Key.Substring(4, 2)}",
                 LearnTimeAvg = (int)g.Where(gx => gx.Mode == 2).Average(gi => gi.ScreenSeconds)
            }).ToList();

Problems happen where there are no records meeting Mode == 2.

Is there a way that I can default LearntTimeAvg to 0 in this case as presently it throws an exception and there's no list created?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

3

You can use DefaultIfEmpty method:

g.Where(gx => gx.Mode == 2).DefaultIfEmpty().Average(gi => gi.ScreenSeconds)

It's usage is:

Returns the elements of an IEnumerable, or a default valued singleton collection if the sequence is empty.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109