All rules
IDE0120Unnecessary code rules (expression-level preferences)
Simplify LINQ expression
Simplify LINQ expression
Microsoft docsDescription
This rule flags overly complex LINQ expressions, specifically expressions that call System.Linq.Enumerable.Where`1(System.Collections.Generic.IEnumerable{0},System.Func{`0,System.Int32,System.Boolean}) followed by one of the following methods:
- System.Linq.Enumerable.Any`
1(System.Collections.Generic.IEnumerable{`0}) - System.Linq.Enumerable.Count`
1(System.Collections.Generic.IEnumerable{`0}) - System.Linq.Enumerable.First`
1(System.Collections.Generic.IEnumerable{`0}) - System.Linq.Enumerable.FirstOrDefault`
1(System.Collections.Generic.IEnumerable{`0}) - System.Linq.Enumerable.Last`
1(System.Collections.Generic.IEnumerable{`0}) - System.Linq.Enumerable.LastOrDefault`
1(System.Collections.Generic.IEnumerable{`0}) - System.Linq.Enumerable.Single`
1(System.Collections.Generic.IEnumerable{`0}) - System.Linq.Enumerable.SingleOrDefault`
1(System.Collections.Generic.IEnumerable{`0})
Such expressions can be simplified by removing the call to System.Linq.Enumerable.Where`1(System.Collections.Generic.IEnumerable{0},System.Func{0,System.Int32,System.Boolean}) and instead calling an overload of Any(), Count(), First(), FirstOrDefault(), Last(), LastOrDefault(), Single, or SingleOrDefault()` that accepts a predicate function to filter the elements.
Example
// Code with violations.
IEnumerable<string> words = new List<string> { "hello", "world", "!" };
var result = words.Where(x => x.Equals("hello")).Any();
// Fixed code.
IEnumerable<string> words = new List<string> { "hello", "world", "!" };
var result = words.Any(x => x.Equals("hello"));Your vote
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0