Skip to content

[API Proposal]: Add IEnumerable<T>.ToReadOnlyList() and ToReadOnlyCollection() extension methods #88018

@dombrovsky

Description

@dombrovsky

Background and motivation

For more straightforward creation of read-only collections from IEnumerable and IAsyncEnumerable.
So it is possible instead of doing Array.AsReadOnly(source.ToArray()) do source.ToReadOnlyCollection().

API Proposal

namespace System.Linq;

public static class Enumerable
{
    public static IReadOnlyCollection<TSource> ToReadOnlyCollection<TSource>(this IEnumerable<TSource> source);

    public static IReadOnlyList<TSource> ToReadOnlyList<TSource>(this IEnumerable<TSource> source);
}

public static class AsyncEnumerable
{
      public static ValueTask<IReadOnlyCollection<TSource>> ToReadOnlyCollectionAsync<TSource>(
            this IAsyncEnumerable<TSource> source,
            CancellationToken cancellationToken = default(CancellationToken));

      public static ValueTask<IReadOnlyList<TSource>> ToReadOnlyListAsync<TSource>(
            this IAsyncEnumerable<TSource> source,
            CancellationToken cancellationToken = default(CancellationToken));
}

API Usage

IReadOnlyCollection<int> collection = Enumerable.Range(0, 10).ToReadOnlyCollection();

Alternative Designs

Use ToImmutableArray() from System.Collections.Immutable.
In this case would be nice to have one for IAsyncEnumerable:

public static ValueTask<ImmutableArray<TSource>> ToImmutableArrayAsync<TSource>(
            this IAsyncEnumerable<TSource> source,
            CancellationToken cancellationToken = default(CancellationToken));

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Linqneeds-author-actionAn issue or pull request that requires more info or actions from the author.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions