CollectionExtensions.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Collections.Generic;
  2. namespace MediaBrowser.Common.Extensions
  3. {
  4. // The MS CollectionExtensions are only available in netcoreapp
  5. public static class CollectionExtensions
  6. {
  7. public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key)
  8. {
  9. dictionary.TryGetValue(key, out var ret);
  10. return ret;
  11. }
  12. /// <summary>
  13. /// Copies all the elements of the current collection to the specified list
  14. /// starting at the specified destination array index. The index is specified as a 32-bit integer.
  15. /// </summary>
  16. /// <param name="source">The current collection that is the source of the elements.</param>
  17. /// <param name="destination">The list that is the destination of the elements copied from the current collection.</param>
  18. /// <param name="index">A 32-bit integer that represents the index in <c>destination</c> at which copying begins.</param>
  19. /// <typeparam name="T"></typeparam>
  20. public static void CopyTo<T>(this IReadOnlyList<T> source, IList<T> destination, int index = 0)
  21. {
  22. for (int i = 0; i < source.Count; i++)
  23. {
  24. destination[index + i] = source[i];
  25. }
  26. }
  27. /// <summary>
  28. /// Copies all the elements of the current collection to the specified list
  29. /// starting at the specified destination array index. The index is specified as a 32-bit integer.
  30. /// </summary>
  31. /// <param name="source">The current collection that is the source of the elements.</param>
  32. /// <param name="destination">The list that is the destination of the elements copied from the current collection.</param>
  33. /// <param name="index">A 32-bit integer that represents the index in <c>destination</c> at which copying begins.</param>
  34. /// <typeparam name="T"></typeparam>
  35. public static void CopyTo<T>(this IReadOnlyCollection<T> source, IList<T> destination, int index = 0)
  36. {
  37. foreach (T item in source)
  38. {
  39. destination[index++] = item;
  40. }
  41. }
  42. }
  43. }