dotnet / roslynator

Roslynator is a set of code analysis tools for C#, powered by Roslyn.

Home Page:https://josefpihrt.github.io/docs/roslynator

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feat(List): "Exists" method should be used instead of the "Any"

dylanvdmerwe opened this issue · comments

Product and Version Used:
4.12.0

Both the List.Exists method and IEnumerable.Any method can be used to find the first element that satisfies a predicate in a collection. However, List.Exists can be faster than IEnumerable.Any for List objects, as well as requires significantly less memory. For small collections, the performance difference may be negligible, but for large collections, it can be noticeable. The same applies to ImmutableList and arrays too.

Original

bool ContainsEven(List<int> data) =>
    data.Any(x => x % 2 == 0);

bool ContainsEven(int[] data) =>
    data.Any(x => x % 2 == 0);

Fix

bool ContainsEven(List<int> data) =>
    data.Exists(x => x % 2 == 0);

bool ContainsEven(int[] data) =>
    Array.Exists(data, x => x % 2 == 0);

Note should also work for classes that inherit from List.