-
Notifications
You must be signed in to change notification settings - Fork 5
Version 7.x.x ToReadOnlyCollection
Pawel Gerr edited this page Aug 21, 2025
·
1 revision
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);- Home
- Smart Enums
- Value Objects
- Discriminated Unions
- Object Factories
- Analyzer Diagnostics
- Source Generator Configuration
- Convenience methods and classes
- Migrations
- Version 7
- Version 8