Why is this an issue?
In the interests of readability, code that can be simplified should be simplified. To that end, there are several ways IEnumerable
language integrated queries (LINQ) can be simplified
- Use
OfType
instead of using Select
with as
to type cast elements and then null-checking in a query
expression to choose elements based on type.
- Use
OfType
instead of using Where
and the is
operator, followed by a cast in a Select
- Use an expression in
Any
instead of Where(element => [expression]).Any()
.
- Use
Count
instead of Count()
when it’s available.
- Don’t call
ToArray()
or ToList()
in the middle of a query chain.
Using EntityFramework
may require enforcing client evaluations. Such queries should use AsEnumerable()
instead of
ToArray()
or ToList()
in the middle of a query chain.
Noncompliant code example
seq1.Select(element => element as T).Any(element => element != null); // Noncompliant; use OfType
seq2.Select(element => element as T).Any(element => element != null && CheckCondition(element)); // Noncompliant; use OfType
seq3.Where(element => element is T).Select(element => element as T); // Noncompliant; use OfType
seq4.Where(element => element is T).Select(element => (T)element); // Noncompliant; use OfType
seq5.Where(element => [expression]).Any(); // Noncompliant; use Any([expression])
var num = seq6.Count(); // Noncompliant
var arr = seq.ToList().ToArray(); //Noncompliant
var count = seq.ToList().Count(x=>[condition]); //Noncompliant
Compliant solution
seq1.OfType<T>().Any();
seq2.OfType<T>().Any(element => CheckCondition(element));
seq3.OfType<T>();
seq4.OfType<T>();
seq5.Any(element => [expression])
var num = seq6.Count;
var arr = seq.ToArray();
var count = seq.Count(x=>[condition]);