Sign in to track progress and bookmarks.
Finding the extremes and the middle ground in your data streams.
Returns the smallest or largest value in a sequence. You can also pass a selector: users.Max(u => u.LastLoginDate) to find the most recent login without sorting the whole list. This is an O(N) operation and is very efficient.
Calculates the mean of a sequence. **Warning:** If the sequence is empty, Average() will throw an InvalidOperationException. **Architect Tip:** Always check .Any() before calling .Average(), or use null-coalescing on the result to provide a default value of 0.
// Safe way to get average
var avg = orders.Any() ? orders.Average(o => o.Total) : 0;
Q: "How do I handle Min/Max on empty sequences?"
Architect Answer: "Use the **DefaultIfEmpty()** method. myList.DefaultIfEmpty(0).Max(). This ensures that if the list is empty, it 'injects' a 0 into the stream, so the Max function has something to return instead of crashing your production server."
Quizzes linked to this course—pass to earn certificates.
On this page
1. Min and Max 2. Average 3. Architect Insight