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. This not only improves readabilty but can also lead to improved performance.
Simplify the LINQ expressions:
OfType instead of using Where and the
is operator, followed
by a cast in a Select Any instead of Where(element ⇒ [expression]).Any(). Using Entity Framework may require enforcing client evaluations. Such queries should use AsEnumerable() instead of ToArray() or
ToList() in the middle of a query chain.
public void Foo(IEnumerable<Vehicle> seq, List<int> list)
{
var result1 = seq.Select(x => x as Car).Any(x => x != null); // Noncompliant; use OfType
var result2 = seq.Select(x => x as Car).Any(x => x != null && x.HasOwner); // Noncompliant; use OfType before calling Any
var result3 = seq.Where(x => x is Car).Select(x => x as Car); // Noncompliant; use OfType
var result4 = seq.Where(x => x is Car).Select(x => (Car)x); // Noncompliant; use OfType
var result5 = seq.Where(x => x.HasOwner).Any(); // Noncompliant; use Any([predicate])
var num = list.Count(); // Noncompliant; use the Count property
var arr = seq.ToList().ToArray(); // Noncompliant; ToList is not needed
var count = seq.ToList().Count(x => x.HasOwner); // Noncompliant; ToList is not needed
}
public void Foo(IEnumerable<Vehicle> seq, List<int> list)
{
var result1 = seq.OfType<Car>().Any();
var result2 = seq.OfType<Car>().Any(x => x.HasOwner);
var result3 = seq.OfType<Car>();
var result4 = seq.OfType<Car>();
var result5 = seq.Any(x => x.HasOwner);
var num = list.Count;
var arr = seq.ToArray();
var count = seq.Count(x => x.HasOwner);
}