namespace Unosquare.Swan
{
using System;
using System.Collections.Generic;
using System.Linq;
///
/// Functional programming extension methods.
///
public static class FunctionalExtensions
{
///
/// Whens the specified condition.
///
/// The type of IQueryable.
/// The list.
/// The condition.
/// The function.
///
/// The IQueryable.
///
///
/// this
/// or
/// condition
/// or
/// fn.
///
public static IQueryable When(
this IQueryable list,
Func condition,
Func, IQueryable> fn)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (condition == null)
throw new ArgumentNullException(nameof(condition));
if (fn == null)
throw new ArgumentNullException(nameof(fn));
return condition() ? fn(list) : list;
}
///
/// Whens the specified condition.
///
/// The type of IEnumerable.
/// The list.
/// The condition.
/// The function.
///
/// The IEnumerable.
///
///
/// this
/// or
/// condition
/// or
/// fn.
///
public static IEnumerable When(
this IEnumerable list,
Func condition,
Func, IEnumerable> fn)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (condition == null)
throw new ArgumentNullException(nameof(condition));
if (fn == null)
throw new ArgumentNullException(nameof(fn));
return condition() ? fn(list) : list;
}
///
/// Adds the value when the condition is true.
///
/// The type of IList element.
/// The list.
/// The condition.
/// The value.
///
/// The IList.
///
///
/// this
/// or
/// condition
/// or
/// value.
///
public static IList AddWhen(
this IList list,
Func condition,
Func value)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (condition == null)
throw new ArgumentNullException(nameof(condition));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (condition())
list.Add(value());
return list;
}
///
/// Adds the value when the condition is true.
///
/// The type of IList element.
/// The list.
/// if set to true [condition].
/// The value.
///
/// The IList.
///
/// list.
public static IList AddWhen(
this IList list,
bool condition,
T value)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (condition)
list.Add(value);
return list;
}
///
/// Adds the range when the condition is true.
///
/// The type of List element.
/// The list.
/// The condition.
/// The value.
///
/// The List.
///
///
/// this
/// or
/// condition
/// or
/// value.
///
public static List AddRangeWhen(
this List list,
Func condition,
Func> value)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (condition == null)
throw new ArgumentNullException(nameof(condition));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (condition())
list.AddRange(value());
return list;
}
}
}