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

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

Open
dylanvdmerwe opened this issue Apr 3, 2024 · 0 comments
Open

Comments

@dylanvdmerwe
Copy link

dylanvdmerwe commented Apr 3, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants