Skip to content

Add new shared SelectXXXAsArray helpers #11796

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

DustinCampbell
Copy link
Member

This adds a handful of new SelectXXXAsArray extension methods and overloads. In particular, there are new SelectAndOrderXXXAsArray methods that transform elements and order them in a single pass.

Add helpers that combine Select And Order/OrderBy/OrderDescending/OrderByDescending to avoid a common LINQ anti-pattern:

```C#
List<int> list = [1, 2, 3, 4, 5];
var result = list.Select(x => x * 2).OrderDescendingAsArray();
```

The code above results in extra allocations by the LINQ Select(...) method, even though the expected results in an ImmutableArray<int>. With these helpers in place, the code above can be written more efficiently as:

```C#
List<int> list = [1, 2, 3, 4, 5];
var result = list.SelectAndOrderDescendingAsArray(x => x * 2);
```
LINQ provides a Select(...) overload where the selector takes an int representing the item index. This change adds a similar overload for SelectAsArray.
Use TryGetCount(...) to retrieve a capacity up front before creating a PooledArrayBuilder<T>.
The type tests for ImmutableArray<T> and IReadOnlyList<T> aren't needed in SelectAndOrderXXXAsArray helpers, since those tests are already performed by their calls to SelectAsArray.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants