using System;
using System.Collections.Generic;
namespace JM.LinqFaster
{
public static partial class LinqFaster
{
// -------------------------- ARRAYS --------------------------------------------
///
/// Filters a sequence of values based on a predicate.
///
/// A sequence to filter.
/// A function to test each element for a condition.
/// A sequence that contains elements from the input sequence that satisfy the condition.
public static T[] WhereF(this T[] source, Func predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
T[] result = new T[source.Length];
int idx = 0;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
{
result[idx] = source[i];
idx++;
}
}
Array.Resize(ref result, idx);
return result;
}
///
/// Filters a sequence of values based on a predicate that includes the index in it's logic.
///
/// A sequence to filter.
/// A function to test each element for a condition along with the element's index.
/// A sequence that contains elements from the input sequence that satisfy the condition.
public static T[] WhereF(this T[] source, Func predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
T[] result = new T[source.Length];
int idx = 0;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i], i))
{
result[idx] = source[i];
idx++;
}
}
Array.Resize(ref result, idx);
return result;
}
// -------------------------- LISTS --------------------------------------------
///
/// Filters a sequence of values based on a predicate.
///
/// A sequence to filter.
/// A function to test each element for a condition.
/// A sequence that contains elements from the input sequence that satisfy the condition.
public static List WhereF(this List source, Predicate predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
return source.FindAll(predicate);
}
///
/// Filters a sequence of values based on a predicate that includes the index in it's logic.
///
/// A sequence to filter.
/// A function to test each element for a condition along with the element's index.
/// A sequence that contains elements from the input sequence that satisfy the condition.
public static List WhereF(this List source, Func predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
List r = new List();
for (int i = 0; i < source.Count; i++)
{
if (predicate(source[i], i)) r.Add(source[i]);
}
return r;
}
}
}