Skip to content

ToReadOnlyCollection

Pawel Gerr edited this page Mar 4, 2023 · 1 revision

ToReadOnlyCollection

Convenience methods for projections (Select) and IEnumerable<T> to save copying a collection to get an IReadOnlyCollection<T>.

// We have to call this method
public void SomeMethod(IReadOnlyCollection<string> userNames)
{
    ...
}

----------

List<User> users = ...;

// Option 1: create a copy with user names, which requires a lot of memory with huge collections.
List<string> userNames = users.Select(u => u.Name).ToList();
SomeMethod(userNames);

// Option 2: use `ToReadOnlyCollection` on users and provide the selector to the method.
IReadOnlyCollection<string> userNames = users.ToReadOnlyCollection(u => u.Name);
SomeMethod(userNames);

// Option 3: use `ToReadOnlyCollection` on `IEnumerable<T>` and provide the number of items to the method.
IReadOnlyCollection<string> userNames = users.Select(u => u.Name).ToReadOnlyCollection(users.Count);
SomeMethod(userNames);