Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Jun 17, 2024
Merged

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

merged 2 commits into from
Jun 17, 2024

Conversation

Djoums
Copy link
Contributor

@Djoums Djoums commented Jun 10, 2024

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;
}

@Djoums Djoums self-assigned this Jun 10, 2024
@Djoums Djoums added 🚀 enhancement New feature or request 🗃️ rule rule improvment or rule development or bug csharp ✨ challenge2024 ✨ Work done during the ecoCode Challenge 2024 labels Jun 10, 2024
@Djoums Djoums requested a review from dedece35 June 15, 2024 10:26
@Djoums Djoums merged commit 0e1f56b into main Jun 17, 2024
1 check passed
@Djoums Djoums deleted the rule/EC91 branch June 17, 2024 14:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🗃️ rule rule improvment or rule development or bug ✨ challenge2024 ✨ Work done during the ecoCode Challenge 2024 csharp 🚀 enhancement New feature or request
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants