You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

CollectionExtensions.cs 2.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. namespace Discord
  7. {
  8. internal static class CollectionExtensions
  9. {
  10. //public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TValue>(this IReadOnlyCollection<TValue> source)
  11. // => new CollectionWrapper<TValue>(source, () => source.Count);
  12. public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TValue>(this ICollection<TValue> source)
  13. => new CollectionWrapper<TValue>(source, () => source.Count);
  14. //public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> source)
  15. // => new CollectionWrapper<TValue>(source.Select(x => x.Value), () => source.Count);
  16. public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TKey, TValue>(this IDictionary<TKey, TValue> source)
  17. => new CollectionWrapper<TValue>(source.Select(x => x.Value), () => source.Count);
  18. public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TValue, TSource>(this IEnumerable<TValue> query, IReadOnlyCollection<TSource> source)
  19. => new CollectionWrapper<TValue>(query, () => source.Count);
  20. public static IReadOnlyCollection<TValue> ToReadOnlyCollection<TValue>(this IEnumerable<TValue> query, Func<int> countFunc)
  21. => new CollectionWrapper<TValue>(query, countFunc);
  22. }
  23. [DebuggerDisplay(@"{DebuggerDisplay,nq}")]
  24. internal struct CollectionWrapper<TValue> : IReadOnlyCollection<TValue>
  25. {
  26. private readonly IEnumerable<TValue> _query;
  27. private readonly Func<int> _countFunc;
  28. //It's okay that this count is affected by race conditions - we're wrapping a concurrent collection and that's to be expected
  29. public int Count => _countFunc();
  30. public CollectionWrapper(IEnumerable<TValue> query, Func<int> countFunc)
  31. {
  32. _query = query;
  33. _countFunc = countFunc;
  34. }
  35. private string DebuggerDisplay => $"Count = {Count}";
  36. public IEnumerator<TValue> GetEnumerator() => _query.GetEnumerator();
  37. IEnumerator IEnumerable.GetEnumerator() => _query.GetEnumerator();
  38. }
  39. }