green-code-initiative / ecoCode

Reduce the environmental footprint of your software programs with SonarQube
https://ecocode.io
GNU General Public License v3.0
139 stars 76 forks source link

[EC91] [C#] Use Where before OrderBy #341

Closed Djoums closed 3 months ago

Djoums commented 3 months ago

Why is this an issue ?

When Orderby is called right before Where, LINQ sorts all the elements before filtering them. Doing the opposite is more efficient, first filter the items then sort the remaining ones only.

When can it be ignored ?

This rule shouldn't be ignored.

Non-compliant examples

public static async Task Test()
{
    var query = items
        .OrderBy(x => x)
        .Where(x => x > 10);
}

public static async Task Test()
{
    var query = items
        .OrderBy(x => x)
        .ThenByDescending(x => x)
        .Where(x => x > 10);
}

public static async Task Test()
{
    var query = from item in items
                orderby item 
                where item > 10
                select item;
}

public static async Task Test()
{
    var query = from item in items
                orderby item descending
                where item > 10
                select item;
}

Compliant examples

public static async Task Test()
{
    var query = items
        .Where(x => x > 10)
        .OrderBy(x => x);
}

public static async Task Test()
{
    var query = items
        .Where(x => x > 10)
        .OrderBy(x => x)
        .ThenByDescending(x => x);
}

public static async Task Test()
{
    var query = from item in items
                where item > 10
                orderby item 
                select item;
}

public static async Task Test()
{
    var query = from item in items
                where item > 10
                orderby item descending
                select item;
}