-
Notifications
You must be signed in to change notification settings - Fork 1
Version 6.x.x ToReadOnlyCollection
Pawel Gerr edited this page Oct 8, 2023
·
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);