From b30e279cbf3d6a1649e185e02cd605894926aded Mon Sep 17 00:00:00 2001 From: lateapexearlyspeed <lateapexearlyspeed@163.com> Date: Wed, 3 Apr 2024 22:02:48 +0800 Subject: [PATCH] Make ToDictionary() selectors parallel. --- .../src/System/Linq/ParallelEnumerable.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs index 55ef371ea04226..78738af5382a04 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs @@ -4964,18 +4964,17 @@ public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>( // comparer may be null. In that case, the Dictionary constructor will use the default comparer. Dictionary<TKey, TSource> result = new Dictionary<TKey, TSource>(comparer); - QueryOperator<TSource>? op = source as QueryOperator<TSource>; - IEnumerator<TSource> input = (op == null) ? source.GetEnumerator() : op.GetEnumerator(ParallelMergeOptions.FullyBuffered, true); + ParallelQuery<KeyValuePair<TKey, TSource>> keyValuePairs = source.Select(item => KeyValuePair.Create(keySelector(item), item)); + Debug.Assert(keyValuePairs is QueryOperator<KeyValuePair<TKey, TSource>>); + IEnumerator<KeyValuePair<TKey, TSource>> input = ((QueryOperator<KeyValuePair<TKey, TSource>>)keyValuePairs).GetEnumerator(ParallelMergeOptions.FullyBuffered, true); using (input) { while (input.MoveNext()) { - TKey key; - TSource val = input.Current; + var (key, val) = input.Current; try { - key = keySelector(val); result.Add(key, val); } catch (Exception ex) @@ -5062,18 +5061,19 @@ public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>( // comparer may be null. In that case, the Dictionary constructor will use the default comparer. Dictionary<TKey, TElement> result = new Dictionary<TKey, TElement>(comparer); - QueryOperator<TSource>? op = source as QueryOperator<TSource>; - IEnumerator<TSource> input = (op == null) ? source.GetEnumerator() : op.GetEnumerator(ParallelMergeOptions.FullyBuffered, true); + ParallelQuery<KeyValuePair<TKey, TElement>> keyValuePairs = source.Select(item => KeyValuePair.Create(keySelector(item), elementSelector(item))); + Debug.Assert(keyValuePairs is QueryOperator<KeyValuePair<TKey, TElement>>); + IEnumerator<KeyValuePair<TKey, TElement>> input = ((QueryOperator<KeyValuePair<TKey, TElement>>)keyValuePairs).GetEnumerator(ParallelMergeOptions.FullyBuffered, true); using (input) { while (input.MoveNext()) { - TSource src = input.Current; + var (key, val) = input.Current; try { - result.Add(keySelector(src), elementSelector(src)); + result.Add(key, val); } catch (Exception ex) {