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
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. OfType instead of using Where and the is operator, followed by a cast in a Select Any instead of Where(element => [expression]).Any(). Count instead of Count() when it’s available. 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.
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
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]);