Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Missed opportunity to use Select

ID: cs/linq/missed-selectKind: 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

It is common to see loops that immediately compute a value from their iteration variable and then never use the iteration variable again in the rest of the loop (see example below). The intent of such loops is arguably not to iterate over the original sequence at all, but to iterate over the sequence that results from transforming the original sequence in some manner.

Recommendation

There is a good case to be made that the code is more readable if this intent is expressed explicitly, which can be done by using LINQ to perform aSelect on the input sequence. The resulting code is clearer due to better separation of concerns.

Example

This example iterates over a list of i2.

classMissedSelectOpportunity{publicstaticvoidMain(string[]args){List<int>lst=Enumerable.Range(1,5).ToList();foreach(intiinlst){intj=i*i;Console.WriteLine(j);}}}

This could be better expressed by using LINQ’sSelect method with a lambda expression.

classMissedSelectOpportunityFix{publicstaticvoidMain(string[]args){List<int>lst=Enumerable.Range(1,5).ToList();foreach(intjinlst.Select(i=>i*i)){Console.WriteLine(j);}}}

References


[8]ページ先頭

©2009-2025 Movatter.jp