Lesson 12/31

Tutorials LINQ Mastery

Min, Max, Average: Statistical operations

On this page

Analytics in LINQ

Finding the extremes and the middle ground in your data streams.

1. Min and Max

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.

2. Average

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;
    

3. Architect Insight

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."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

LINQ Mastery
Course syllabus
General
1. Core Foundations
2. Filtering & Transformation
3. Aggregation & Quantifiers
4. Ordering & Partitioning
5. Sets & Lookups
6. Join & Grouping
7. Advanced Providers & Parallelism
8. Real-world Performance & Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details