All files
[pithos-ms-client] / trunk / Libraries / ParallelExtensionsExtras / ParallelAlgorithms / ParallelAlgorithms_Filter.cs
1 //--------------------------------------------------------------------------
2 // 
3 //  Copyright (c) Microsoft Corporation.  All rights reserved. 
4 // 
5 //  File: ParallelAlgorithms_Filter.cs
6 //
7 //--------------------------------------------------------------------------
8
9 using System.Collections.Generic;
10 using System.Threading.Tasks;
11
12 namespace System.Threading.Algorithms
13 {
14     public static partial class ParallelAlgorithms
15     {
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)
22         {
23             return Filter(input, s_defaultParallelOptions, predicate);
24         }
25
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)
33         {
34             if (input == null) throw new ArgumentNullException("input");
35             if (parallelOptions == null) throw new ArgumentNullException("parallelOptions");
36             if (predicate == null) throw new ArgumentNullException("predicate");
37
38             var results = new List<T>(input.Count);
39             Parallel.For(0, input.Count, parallelOptions, () => new List<T>(input.Count), (i, loop, localList) =>
40             {
41                 var item = input[i];
42                 if (predicate(item)) localList.Add(item);
43                 return localList;
44             },
45             localList => { lock (results) results.AddRange(localList); });
46             return results;
47         }
48     }
49 }