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 ToDictionary( // comparer may be null. In that case, the Dictionary constructor will use the default comparer. Dictionary result = new Dictionary(comparer); - QueryOperator? op = source as QueryOperator; - IEnumerator input = (op == null) ? source.GetEnumerator() : op.GetEnumerator(ParallelMergeOptions.FullyBuffered, true); + ParallelQuery> keyValuePairs = source.Select(item => KeyValuePair.Create(keySelector(item), item)); + Debug.Assert(keyValuePairs is QueryOperator>); + IEnumerator> input = ((QueryOperator>)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 ToDictionary( // comparer may be null. In that case, the Dictionary constructor will use the default comparer. Dictionary result = new Dictionary(comparer); - QueryOperator? op = source as QueryOperator; - IEnumerator input = (op == null) ? source.GetEnumerator() : op.GetEnumerator(ParallelMergeOptions.FullyBuffered, true); + ParallelQuery> keyValuePairs = source.Select(item => KeyValuePair.Create(keySelector(item), elementSelector(item))); + Debug.Assert(keyValuePairs is QueryOperator>); + IEnumerator> input = ((QueryOperator>)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) {