Skip to content

API proposal: Find methods for ImmutableArray #45366

Open

Description

@acaly

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 5

Alternative Designs

  1. 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.
  2. 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 in Array, List<T>, and ImmutableList<T>.
  3. 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 the ImmutableArray<T>. I am not sure the future shape feature can provide uniformed solution.
  4. Func<T, bool> may be used instead of Predicate<T>. More modern APIs tend to use the former. Note that ImmutableList<T> also uses Predicate<T>.
  5. As noted in Proposed API section above, some methods have been added to ImmutableArrayExtensions with 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 in ImmutableArray or ImmutableArray<T>.

Risks

Other notes

There are other methods that ImmutableList<T> has but ImmutableArray currently does not have:

Activity

  1. added
    api-suggestion
    on Nov 30, 2020
  2. added
    untriaged
    on Nov 30, 2020
  3. eiriktsarpalis commented on Dec 1, 2020

    @eiriktsarpalis
    Member

    Thank you for this well-written API proposal. A few remarks:

    • Should we be using Predicate<T> or Func<T, bool>? I know the current shape reflects the APIs of System.Array but I believe more modern APIs tend to use the latter. Note that ImmutableList also uses Predicate<T> so perhaps that answers my question.
    • The equivalent methods in 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.
    • Playing devil's advocate, System.Linq already offers some of the functionality proposed here. The System.Array methods do offer better performance, however it does beg the question if raw performance is a significant requirement for immutable collections.

    @stephentoub thoughts?

  4. acaly commented on Dec 1, 2020

    @acaly
    Author

    Thanks for the feedback. I have updated the proposal.

    The System.Array methods do offer better performance, however it does beg the question if raw performance is a significant requirement for immutable collections.

    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.

  5. removed
    untriaged
    on Dec 9, 2020
  6. added this to the Future milestone on Dec 9, 2020
  7. acaly commented on Jul 28, 2021

    @acaly
    Author

    Will this API be considered hopefully in 7.0?

  8. modified the milestones: Future, 7.0.0 on Jul 28, 2021
  9. eiriktsarpalis commented on Jul 28, 2021

    @eiriktsarpalis
    Member

    We can certainly take a look. I have updated the milestone.

  10. eiriktsarpalis commented on Oct 26, 2021

    @eiriktsarpalis
    Member

    Related to #22928.

  11. jeffhandley commented on Jul 9, 2022

    @jeffhandley
    Member

    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?

  12. modified the milestones: 7.0.0, 8.0.0 on Jul 9, 2022
  13. eiriktsarpalis commented on Jul 9, 2022

    @eiriktsarpalis
    Member

    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.

  14. acaly commented on Jul 9, 2022

    @acaly
    Author

    Would a built-in solution provide substantial performance benefits over a user-provided extension method?

    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.

  15. modified the milestones: 8.0.0, Future on Oct 7, 2022
  16. added
    wishlist
    on Oct 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Collectionswishlist

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions