CodeQL documentation

Missed opportunity to use Select

ID: cs/linq/missed-select
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - maintainability
   - language-features
Query 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 a Select on the input sequence. The resulting code is clearer due to better separation of concerns.

Example

This example iterates over a list of i2.

class MissedSelectOpportunity
{
    public static void Main(string[] args)
    {
        List<int> lst = Enumerable.Range(1, 5).ToList();

        foreach (int i in lst)
        {
            int j = i * i;
            Console.WriteLine(j);
        }
    }
}

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

class MissedSelectOpportunityFix
{
    public static void Main(string[] args)
    {
        List<int> lst = Enumerable.Range(1, 5).ToList();

        foreach (int j in lst.Select(i => i * i))
        {
            Console.WriteLine(j);
        }
    }
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy