ReadOnlyCollectionExtensions.cs 1.4 KB

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