ReadOnlyListExtension.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Jellyfin.Extensions
  4. {
  5. /// <summary>
  6. /// Static extensions for the <see cref="IReadOnlyList{T}"/> interface.
  7. /// </summary>
  8. public static class ReadOnlyListExtension
  9. {
  10. /// <summary>
  11. /// Finds the index of the desired item.
  12. /// </summary>
  13. /// <param name="source">The source list.</param>
  14. /// <param name="value">The value to fine.</param>
  15. /// <typeparam name="T">The type of item to find.</typeparam>
  16. /// <returns>Index if found, else -1.</returns>
  17. public static int IndexOf<T>(this IReadOnlyList<T> source, T value)
  18. {
  19. if (source is IList<T> list)
  20. {
  21. return list.IndexOf(value);
  22. }
  23. for (int i = 0; i < source.Count; i++)
  24. {
  25. if (Equals(value, source[i]))
  26. {
  27. return i;
  28. }
  29. }
  30. return -1;
  31. }
  32. /// <summary>
  33. /// Finds the index of the predicate.
  34. /// </summary>
  35. /// <param name="source">The source list.</param>
  36. /// <param name="match">The value to find.</param>
  37. /// <typeparam name="T">The type of item to find.</typeparam>
  38. /// <returns>Index if found, else -1.</returns>
  39. public static int FindIndex<T>(this IReadOnlyList<T> source, Predicate<T> match)
  40. {
  41. if (source is List<T> list)
  42. {
  43. return list.FindIndex(match);
  44. }
  45. for (int i = 0; i < source.Count; i++)
  46. {
  47. if (match(source[i]))
  48. {
  49. return i;
  50. }
  51. }
  52. return -1;
  53. }
  54. }
  55. }