Repository navigation
Description
Background and Motivation
ImmutableArray, as a simple immutable wrapper of array, has its advantages of performance and readability in the API design of any libraries which expose data that never changes. For such exposed data, finding elements with a Predictate is common. This includes finding the actual element (T for ImmutableArray<T>) and finding the index. These methods exist for System.Array (as static methods) and ImmutableList<T> (as instance methods), but for ImmutableArray<T>, there are no such methods and it would require one to manually enumerate and check for each element, especially when an index, instead of the element, is needed.
Proposed API
namespace System.Collections.Immutable
{
public static class ImmutableArray {
//Find single element.
+ public static T Find<T>(this ImmutableArray<T> array, Predicate<T> match);
+ public static T FindLast<T>(this ImmutableArray<T> array, Predicate<T> match);
//Find all elements.
+ public static ImmutableArray<T> FindAll<T>(this ImmutableArray<T> array, Predicate<T> match);
//Find single element returning index, with optional index range.
+ public static int FindIndex<T>(this ImmutableArray<T> array, Predicate<T> match);
+ public static int FindIndex<T>(this ImmutableArray<T> array, int startIndex, Predicate<T> match);
+ public static int FindIndex<T>(this ImmutableArray<T> array, int startIndex, int count, Predicate<T> match);
+ public static int FindLastIndex<T>(this ImmutableArray<T> array, Predicate<T> match);
+ public static int FindLastIndex<T>(this ImmutableArray<T> array, int startIndex, Predicate<T> match);
+ public static int FindLastIndex<T>(this ImmutableArray<T> array, int startIndex, int count, Predicate<T> match);
//Check returning only true or false.
+ public static bool Exists<T>(this ImmutableArray<T> array, Predicate<T> match);
+ public static bool TrueForAll<T>(this ImmutableArray<T> array, Predicate<T> match);
}
}EDIT: Find, FindLast, Exists and TrueForAll are not necessary, because there are already First, Last, Any and All in ImmutableArrayExtensions class, which serve exactly the same purpose.
Usage Examples
This is a example rewritten with immutable array from the one in the official document of List<T>.FindIndex.
using System;
using System.Collections.Generic;
public record Employee(string Name, int Id);
public class EmployeeSearch
{
private readonly string _s;
public EmployeeSearch(string s)
{
_s = s;
}
public bool StartsWith(Employee e)
{
return e.Name.StartsWith(_s, StringComparison.InvariantCultureIgnoreCase);
}
}
public class Example
{
public static void Main()
{
var builder = ImmutableArray.CreateBuilder<Employee>();
builder.AddRange(new Employee[]
{
new Employee("Frank", 2),
new Employee("Jill", 3),
new Employee("Dave", 5),
new Employee("Jack", 8),
new Employee("Judith", 12),
new Employee("Robert", 14),
new Employee("Adam", 1),
});
builder.Sort((e1, e2) => string.Compare(e1.Name, e2.Name, StringComparison.InvariantCultureIgnoreCase));
var employees = builder.ToImmutable();
var es = new EmployeeSearch("J");
Console.WriteLine("'J' starts at index {0}",
employees.FindIndex(es.StartsWith));
es = new EmployeeSearch("Ju");
Console.WriteLine("'Ju' starts at index {0}",
employees.FindIndex(es.StartsWith));
}
}
// The example displays the following output:
// 'J' starts at index 3
// 'Ju' starts at index 5Alternative Designs
- These methods may also be added as members of
struct ImmutableArray<T>. However, binary search methods of immutable array have been added as extension methods with the consideration of runtime overhead. Find methods should be in consistent. - These methods may also be added as members of
class ImmutableArrayExtensions, where Linq equivalent methods have been added. However, I believe Linq is an extension to collections, and has less performance consideration, while Find should be within the function of collections instead of extension, as has been the case for Find inArray,List<T>, andImmutableList<T>. - These methods may also be added instead as extension methods of
IList<T>interface. However, this would require additional boxing for value types such as theImmutableArray<T>. I am not sure the future shape feature can provide uniformed solution. Func<T, bool>may be used instead ofPredicate<T>. More modern APIs tend to use the former. Note thatImmutableList<T>also usesPredicate<T>.- As noted in Proposed API section above, some methods have been added to
ImmutableArrayExtensionswith different names. However, those are considered part of Linq library as an extension and for similar reasons as 2., at least Find methods should be provided inImmutableArrayorImmutableArray<T>.
Risks
Other notes
There are other methods that ImmutableList<T> has but ImmutableArray currently does not have:
Activity
eiriktsarpalis commentedon Dec 1, 2020
Thank you for this well-written API proposal. A few remarks:
Predicate<T>orFunc<T, bool>? I know the current shape reflects the APIs ofSystem.Arraybut I believe more modern APIs tend to use the latter. Note thatImmutableListalso usesPredicate<T>so perhaps that answers my question.ImmutableList<T>are instance methods and not extension methods. There is always a runtime cost with including instance methods in generic types, so probably extension methods are more appropriate for this addition.@stephentoub thoughts?
acaly commentedon Dec 1, 2020
Thanks for the feedback. I have updated the proposal.
I agree that that bit of performance difference is beyond consideration of many people using C# or VB.NET. However, FindIndex is something Linq cannot have. There has been duplicate methods for Find in Linq and other collections (eg. Array and List). In my opinion, adding the same Find and FindLast to ImmutableArray together with FindIndex to be consistent is not a problem.
acaly commentedon Jul 28, 2021
Will this API be considered hopefully in 7.0?
eiriktsarpalis commentedon Jul 28, 2021
We can certainly take a look. I have updated the milestone.
eiriktsarpalis commentedon Oct 26, 2021
Related to #22928.
jeffhandley commentedon Jul 9, 2022
We haven't had time to get to this for 7.0; I'm moving it to 8.0.
@dotnet/area-system-collections Is this ready for API review?
eiriktsarpalis commentedon Jul 9, 2022
Before we mark this for review, we might want to investigate whether such an inclusion would provide value to System.Collections.Immutable. What use cases does the inclusion simplify? Would a built-in solution provide substantial performance benefits over a user-provided extension method? I don't think we should be adding LINQ-like APIs to collections unless we have a very strong reason to do it. We can try driving this investigation in the future provided we have available cycles.
acaly commentedon Jul 9, 2022
I don't think so. I think it is just to make it easier for user to access them and thus encourage user to use them instead of normal arrays.
I know that there are many immutable collections and adding these extensions for all of them may bring other issues like maintainence and binary size, which Linq already does today, so I understand if this couldn't be added now.