Skip to content

Instantly share code, notes, and snippets.

@fiddyschmitt
Last active October 17, 2025 03:38
Show Gist options
  • Select an option

  • Save fiddyschmitt/c1c298e0881ac6ba0eb151bb9cee5560 to your computer and use it in GitHub Desktop.

Select an option

Save fiddyschmitt/c1c298e0881ac6ba0eb151bb9cee5560 to your computer and use it in GitHub Desktop.
//This achieves 3 things:
//1. Processes in parallel
//2. Preserves original order
//3. Returns items immediately after they are available
public static IEnumerable<TOutput> SelectParallelPreserveOrder<TInput,TOutput>(
this IEnumerable<TInput> source,
Func<TInput, TOutput> selector,
int? degree = null)
{
var dop = Math.Max(degree ?? Environment.ProcessorCount, 1);
return source
.AsParallel()
.AsOrdered() // preserve source order
.WithDegreeOfParallelism(dop)
.WithMergeOptions(ParallelMergeOptions.NotBuffered) // stream ASAP
.Select(selector)
.AsSequential(); // return as IEnumerable<TOutput>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment