ToLookup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static Task<ILookup<TKey, TSource>> ToLookup<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. if (keySelector == null)
  18. throw new ArgumentNullException(nameof(keySelector));
  19. return ToLookup(source, keySelector, CancellationToken.None);
  20. }
  21. public static Task<ILookup<TKey, TSource>> ToLookup<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, CancellationToken cancellationToken)
  22. {
  23. if (source == null)
  24. throw new ArgumentNullException(nameof(source));
  25. if (keySelector == null)
  26. throw new ArgumentNullException(nameof(keySelector));
  27. return source.ToLookup(keySelector, x => x, EqualityComparer<TKey>.Default, cancellationToken);
  28. }
  29. public static Task<ILookup<TKey, TSource>> ToLookup<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
  30. {
  31. if (source == null)
  32. throw new ArgumentNullException(nameof(source));
  33. if (keySelector == null)
  34. throw new ArgumentNullException(nameof(keySelector));
  35. if (comparer == null)
  36. throw new ArgumentNullException(nameof(comparer));
  37. return ToLookup(source, keySelector, comparer, CancellationToken.None);
  38. }
  39. public static Task<ILookup<TKey, TSource>> ToLookup<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  40. {
  41. if (source == null)
  42. throw new ArgumentNullException(nameof(source));
  43. if (keySelector == null)
  44. throw new ArgumentNullException(nameof(keySelector));
  45. if (comparer == null)
  46. throw new ArgumentNullException(nameof(comparer));
  47. return source.ToLookup(keySelector, x => x, comparer, cancellationToken);
  48. }
  49. public static Task<ILookup<TKey, TElement>> ToLookup<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
  50. {
  51. if (source == null)
  52. throw new ArgumentNullException(nameof(source));
  53. if (keySelector == null)
  54. throw new ArgumentNullException(nameof(keySelector));
  55. if (elementSelector == null)
  56. throw new ArgumentNullException(nameof(elementSelector));
  57. return ToLookup(source, keySelector, elementSelector, CancellationToken.None);
  58. }
  59. public static Task<ILookup<TKey, TElement>> ToLookup<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, CancellationToken cancellationToken)
  60. {
  61. if (source == null)
  62. throw new ArgumentNullException(nameof(source));
  63. if (keySelector == null)
  64. throw new ArgumentNullException(nameof(keySelector));
  65. if (elementSelector == null)
  66. throw new ArgumentNullException(nameof(elementSelector));
  67. return source.ToLookup(keySelector, elementSelector, EqualityComparer<TKey>.Default, cancellationToken);
  68. }
  69. public static Task<ILookup<TKey, TElement>> ToLookup<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
  70. {
  71. if (source == null)
  72. throw new ArgumentNullException(nameof(source));
  73. if (keySelector == null)
  74. throw new ArgumentNullException(nameof(keySelector));
  75. if (elementSelector == null)
  76. throw new ArgumentNullException(nameof(elementSelector));
  77. if (comparer == null)
  78. throw new ArgumentNullException(nameof(comparer));
  79. return ToLookup(source, keySelector, elementSelector, comparer, CancellationToken.None);
  80. }
  81. public static async Task<ILookup<TKey, TElement>> ToLookup<TSource, TKey, TElement>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken)
  82. {
  83. if (source == null)
  84. throw new ArgumentNullException(nameof(source));
  85. if (keySelector == null)
  86. throw new ArgumentNullException(nameof(keySelector));
  87. if (elementSelector == null)
  88. throw new ArgumentNullException(nameof(elementSelector));
  89. if (comparer == null)
  90. throw new ArgumentNullException(nameof(comparer));
  91. var lookup = await Internal.Lookup<TKey, TElement>.CreateAsync(source, keySelector, elementSelector, comparer).ConfigureAwait(false);
  92. return lookup;
  93. }
  94. }
  95. }
  96. // This is internal because System.Linq exposes a public Lookup that we cannot directly use here
  97. namespace System.Linq.Internal
  98. {
  99. internal class Lookup<TKey, TElement> : ILookup<TKey, TElement>, IIListProvider<IAsyncGrouping<TKey, TElement>>
  100. {
  101. private readonly IEqualityComparer<TKey> _comparer;
  102. private Grouping<TKey, TElement>[] _groupings;
  103. private Grouping<TKey, TElement> _lastGrouping;
  104. private Lookup(IEqualityComparer<TKey> comparer)
  105. {
  106. _comparer = comparer ?? EqualityComparer<TKey>.Default;
  107. _groupings = new Grouping<TKey, TElement>[7];
  108. }
  109. public int Count { get; private set; }
  110. public IEnumerable<TElement> this[TKey key]
  111. {
  112. get
  113. {
  114. var grouping = GetGrouping(key, create: false);
  115. if (grouping != null)
  116. {
  117. return grouping;
  118. }
  119. #if NO_ARRAY_EMPTY
  120. return EmptyArray<TElement>.Value;
  121. #else
  122. return Array.Empty<TElement>();
  123. #endif
  124. }
  125. }
  126. public bool Contains(TKey key)
  127. {
  128. return GetGrouping(key, create: false) != null;
  129. }
  130. IEnumerator IEnumerable.GetEnumerator()
  131. {
  132. return GetEnumerator();
  133. }
  134. public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
  135. {
  136. var g = _lastGrouping;
  137. if (g != null)
  138. {
  139. do
  140. {
  141. g = g._next;
  142. yield return g;
  143. } while (g != _lastGrouping);
  144. }
  145. }
  146. public IEnumerable<TResult> ApplyResultSelector<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  147. {
  148. var g = _lastGrouping;
  149. if (g != null)
  150. {
  151. do
  152. {
  153. g = g._next;
  154. g.Trim();
  155. var result = resultSelector(g._key, g._elements.ToAsyncEnumerable());
  156. yield return result;
  157. } while (g != _lastGrouping);
  158. }
  159. }
  160. internal static async Task<Lookup<TKey, TElement>> CreateAsync<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken = default(CancellationToken))
  161. {
  162. Debug.Assert(source != null);
  163. Debug.Assert(keySelector != null);
  164. Debug.Assert(elementSelector != null);
  165. var lookup = new Lookup<TKey, TElement>(comparer);
  166. var enu = source.GetAsyncEnumerator();
  167. try
  168. {
  169. while (await enu.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  170. {
  171. lookup.GetGrouping(keySelector(enu.Current), create: true).Add(elementSelector(enu.Current));
  172. }
  173. }
  174. finally
  175. {
  176. await enu.DisposeAsync().ConfigureAwait(false);
  177. }
  178. return lookup;
  179. }
  180. internal static async Task<Lookup<TKey, TElement>> CreateAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken = default(CancellationToken))
  181. {
  182. Debug.Assert(source != null);
  183. Debug.Assert(keySelector != null);
  184. var lookup = new Lookup<TKey, TElement>(comparer);
  185. var enu = source.GetAsyncEnumerator();
  186. try
  187. {
  188. while (await enu.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  189. {
  190. var key = keySelector(enu.Current);
  191. lookup.GetGrouping(key, create: true).Add(enu.Current);
  192. }
  193. }
  194. finally
  195. {
  196. await enu.DisposeAsync().ConfigureAwait(false);
  197. }
  198. return lookup;
  199. }
  200. internal static async Task<Lookup<TKey, TElement>> CreateForJoinAsync(IAsyncEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer)
  201. {
  202. var lookup = new Lookup<TKey, TElement>(comparer);
  203. var enu = source.GetAsyncEnumerator();
  204. try
  205. {
  206. while (await enu.MoveNextAsync().ConfigureAwait(false))
  207. {
  208. var key = keySelector(enu.Current);
  209. if (key != null)
  210. {
  211. lookup.GetGrouping(key, create: true).Add(enu.Current);
  212. }
  213. }
  214. }
  215. finally
  216. {
  217. await enu.DisposeAsync().ConfigureAwait(false);
  218. }
  219. return lookup;
  220. }
  221. internal Grouping<TKey, TElement> GetGrouping(TKey key, bool create)
  222. {
  223. var hashCode = InternalGetHashCode(key);
  224. for (var g = _groupings[hashCode % _groupings.Length]; g != null; g = g._hashNext)
  225. {
  226. if (g._hashCode == hashCode && _comparer.Equals(g._key, key))
  227. {
  228. return g;
  229. }
  230. }
  231. if (create)
  232. {
  233. if (Count == _groupings.Length)
  234. {
  235. Resize();
  236. }
  237. var index = hashCode % _groupings.Length;
  238. var g = new Grouping<TKey, TElement>
  239. {
  240. _key = key,
  241. _hashCode = hashCode,
  242. _elements = new TElement[1],
  243. _hashNext = _groupings[index]
  244. };
  245. _groupings[index] = g;
  246. if (_lastGrouping == null)
  247. {
  248. g._next = g;
  249. }
  250. else
  251. {
  252. g._next = _lastGrouping._next;
  253. _lastGrouping._next = g;
  254. }
  255. _lastGrouping = g;
  256. Count++;
  257. return g;
  258. }
  259. return null;
  260. }
  261. internal int InternalGetHashCode(TKey key)
  262. {
  263. // Handle comparer implementations that throw when passed null
  264. return (key == null) ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF;
  265. }
  266. internal TResult[] ToArray<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  267. {
  268. var array = new TResult[Count];
  269. var index = 0;
  270. var g = _lastGrouping;
  271. if (g != null)
  272. {
  273. do
  274. {
  275. g = g._next;
  276. g.Trim();
  277. array[index] = resultSelector(g._key, g._elements.ToAsyncEnumerable());
  278. ++index;
  279. } while (g != _lastGrouping);
  280. }
  281. return array;
  282. }
  283. internal List<TResult> ToList<TResult>(Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector)
  284. {
  285. var list = new List<TResult>(Count);
  286. var g = _lastGrouping;
  287. if (g != null)
  288. {
  289. do
  290. {
  291. g = g._next;
  292. g.Trim();
  293. var result = resultSelector(g._key, g._elements.ToAsyncEnumerable());
  294. list.Add(result);
  295. } while (g != _lastGrouping);
  296. }
  297. return list;
  298. }
  299. private void Resize()
  300. {
  301. var newSize = checked((Count * 2) + 1);
  302. var newGroupings = new Grouping<TKey, TElement>[newSize];
  303. var g = _lastGrouping;
  304. do
  305. {
  306. g = g._next;
  307. var index = g._hashCode % newSize;
  308. g._hashNext = newGroupings[index];
  309. newGroupings[index] = g;
  310. } while (g != _lastGrouping);
  311. _groupings = newGroupings;
  312. }
  313. public Task<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
  314. {
  315. return Task.FromResult(Count);
  316. }
  317. IAsyncEnumerator<IAsyncGrouping<TKey, TElement>> IAsyncEnumerable<IAsyncGrouping<TKey, TElement>>.GetAsyncEnumerator()
  318. {
  319. return Enumerable.Cast<IAsyncGrouping<TKey, TElement>>(this).ToAsyncEnumerable().GetAsyncEnumerator();
  320. }
  321. Task<List<IAsyncGrouping<TKey, TElement>>> IIListProvider<IAsyncGrouping<TKey, TElement>>.ToListAsync(CancellationToken cancellationToken)
  322. {
  323. var list = new List<IAsyncGrouping<TKey, TElement>>(Count);
  324. var g = _lastGrouping;
  325. if (g != null)
  326. {
  327. do
  328. {
  329. g = g._next;
  330. list.Add(g);
  331. }
  332. while (g != _lastGrouping);
  333. }
  334. return Task.FromResult(list);
  335. }
  336. Task<IAsyncGrouping<TKey, TElement>[]> IIListProvider<IAsyncGrouping<TKey, TElement>>.ToArrayAsync(CancellationToken cancellationToken)
  337. {
  338. var array = new IAsyncGrouping<TKey, TElement>[Count];
  339. var index = 0;
  340. var g = _lastGrouping;
  341. if (g != null)
  342. {
  343. do
  344. {
  345. g = g._next;
  346. array[index] = g;
  347. ++index;
  348. }
  349. while (g != _lastGrouping);
  350. }
  351. return Task.FromResult(array);
  352. }
  353. }
  354. }