//--------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: ParallelAlgorithms_Filter.cs
//
//--------------------------------------------------------------------------
using System.Collections.Generic;
using System.Threading.Tasks;
namespace System.Threading.Algorithms
{
public static partial class ParallelAlgorithms
{
/// Filters an input list, running a predicate over each element of the input.
/// Specifies the type of data in the list.
/// The list to be filtered.
/// The predicate to use to determine which elements pass.
/// A new list containing all those elements from the input that passed the filter.
public static IList Filter(IList input, Func predicate)
{
return Filter(input, s_defaultParallelOptions, predicate);
}
/// Filters an input list, running a predicate over each element of the input.
/// Specifies the type of data in the list.
/// The list to be filtered.
/// Options to use for the execution of this filter.
/// The predicate to use to determine which elements pass.
/// A new list containing all those elements from the input that passed the filter.
public static IList Filter(IList input, ParallelOptions parallelOptions, Func predicate)
{
if (input == null) throw new ArgumentNullException("input");
if (parallelOptions == null) throw new ArgumentNullException("parallelOptions");
if (predicate == null) throw new ArgumentNullException("predicate");
var results = new List(input.Count);
Parallel.For(0, input.Count, parallelOptions, () => new List(input.Count), (i, loop, localList) =>
{
var item = input[i];
if (predicate(item)) localList.Add(item);
return localList;
},
localList => { lock (results) results.AddRange(localList); });
return results;
}
}
}