Writing efficient LINQ queries in C# is crucial to avoid unnecessary memory allocations and redundant sequence enumerations. ReSharper automatically flags inefficient LINQ expressions and provides instant quick-fixes (Alt+Enter) to optimize performance.
Common Inefficient LINQ Patterns Identified by ReSharper
ReSharper identifies several common anti-patterns in C# LINQ usage, including:
- Using
Count() > 0instead ofAny(). - Multiple enumerations of an
IEnumerable<T>without caching. - Redundant
ToList()orToArray()calls prior to filtering.
Code Refactoring Example
The code sample below illustrates how ReSharper transforms an inefficient collection evaluation into an optimized version:
// Unoptimized pattern flagged by ReSharper
public bool HasActiveUsers(IEnumerable users)
{
return users.Where(u => u.IsActive).Count() > 0;
}
// Optimized pattern suggested by ReSharper
public bool HasActiveUsersOptimized(IEnumerable users)
{
return users.Any(u => u.IsActive);
} Performance Impact
By switching from Count() > 0 to Any(), execution halts as soon as the first matching element is discovered, preventing a full iteration over the entire sequence.