ReadOnlyCollectionExtensions.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #nullable disable
  2. namespace Terminal.Gui.Views;
  3. /// <summary>
  4. /// Extends <see cref="IReadOnlyCollection{T}"/> with methods to find the index of an element.
  5. /// </summary>
  6. public static class ReadOnlyCollectionExtensions
  7. {
  8. /// <summary>
  9. /// Returns the index of the first element in the collection that matches the specified predicate.
  10. /// </summary>
  11. /// <param name="self"></param>
  12. /// <param name="predicate"></param>
  13. /// <typeparam name="T"></typeparam>
  14. /// <returns></returns>
  15. public static int IndexOf<T> (this IReadOnlyCollection<T> self, Func<T, bool> predicate)
  16. {
  17. var i = 0;
  18. foreach (T element in self)
  19. {
  20. if (predicate (element))
  21. {
  22. return i;
  23. }
  24. i++;
  25. }
  26. return -1;
  27. }
  28. /// <summary>
  29. /// Returns the index of the first element in the collection that matches the specified predicate.
  30. /// </summary>
  31. /// <param name="self"></param>
  32. /// <param name="toFind"></param>
  33. /// <typeparam name="T"></typeparam>
  34. /// <returns></returns>
  35. public static int IndexOf<T> (this IReadOnlyCollection<T> self, T toFind)
  36. {
  37. var i = 0;
  38. foreach (T element in self)
  39. {
  40. if (Equals (element, toFind))
  41. {
  42. return i;
  43. }
  44. i++;
  45. }
  46. return -1;
  47. }
  48. }