1 //--------------------------------------------------------------------------
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // File: ParallelAlgorithms_Filter.cs
7 //--------------------------------------------------------------------------
9 using System.Collections.Generic;
10 using System.Threading.Tasks;
12 namespace System.Threading.Algorithms
14 public static partial class ParallelAlgorithms
16 /// <summary>Filters an input list, running a predicate over each element of the input.</summary>
17 /// <typeparam name="T">Specifies the type of data in the list.</typeparam>
18 /// <param name="input">The list to be filtered.</param>
19 /// <param name="predicate">The predicate to use to determine which elements pass.</param>
20 /// <returns>A new list containing all those elements from the input that passed the filter.</returns>
21 public static IList<T> Filter<T>(IList<T> input, Func<T, Boolean> predicate)
23 return Filter(input, s_defaultParallelOptions, predicate);
26 /// <summary>Filters an input list, running a predicate over each element of the input.</summary>
27 /// <typeparam name="T">Specifies the type of data in the list.</typeparam>
28 /// <param name="input">The list to be filtered.</param>
29 /// <param name="parallelOptions">Options to use for the execution of this filter.</param>
30 /// <param name="predicate">The predicate to use to determine which elements pass.</param>
31 /// <returns>A new list containing all those elements from the input that passed the filter.</returns>
32 public static IList<T> Filter<T>(IList<T> input, ParallelOptions parallelOptions, Func<T, Boolean> predicate)
34 if (input == null) throw new ArgumentNullException("input");
35 if (parallelOptions == null) throw new ArgumentNullException("parallelOptions");
36 if (predicate == null) throw new ArgumentNullException("predicate");
38 var results = new List<T>(input.Count);
39 Parallel.For(0, input.Count, parallelOptions, () => new List<T>(input.Count), (i, loop, localList) =>
42 if (predicate(item)) localList.Add(item);
45 localList => { lock (results) results.AddRange(localList); });