ReadOnlyListExtension.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. /// <summary>
  55. /// Get the first or default item from a list.
  56. /// </summary>
  57. /// <param name="source">The source list.</param>
  58. /// <typeparam name="T">The type of item.</typeparam>
  59. /// <returns>The first item or default if list is empty.</returns>
  60. public static T? FirstOrDefault<T>(this IReadOnlyList<T>? source)
  61. {
  62. if (source is null || source.Count == 0)
  63. {
  64. return default;
  65. }
  66. return source[0];
  67. }
  68. }
  69. }