Missed opportunity to use All¶
ID: cs/linq/missed-allKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - quality - maintainability - readability - language-featuresQuery suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Often a programmer wants to check that all the elements of a given sequence satisfy some predicate. A common pattern for this is to create a flag and then iterate over the sequence, changing the flag and breaking out of the loop if the element being examined does not satisfy the predicate.
Recommendation¶
This pattern works well and is also available as theAll method in LINQ. It is better to use a library method in preference to writing your own pattern unless you have a specific need for a custom version. In particular, this makes the code easier to read (the intent is more clearly expressed), shorter, less error-prone and more maintainable.
Example¶
In this example the list is iterated in order to check if every element is even.
classMissedAllOpportunity{publicstaticvoidMain(string[]args){List<int>lst=newList<int>{2,4,18,12,80};boolallEven=true;foreach(intiinlst){if(i%2!=0){allEven=false;break;}}Console.WriteLine("All Even = "+allEven);}}
The LINQAll method can be used to accomplish this in a much simpler fashion.
classMissedAllOpportunityFix{publicstaticvoidMain(string[]args){List<int>lst=newList<int>{2,4,18,12,80};Console.WriteLine("All Even = "+lst.All(i=>i%2==0));}}