这些扩展方法将使您能够枚举每个可能的对(遵循链接到的旧的so python问题中概述的相同命名/约定),并提供请求的anypair方法和foreachpair方法。
public static class EnumerableExtensions
{
public static bool AnyPair<T>(this IEnumerable<T> values,
Func<T, T, bool> predicate)
{
return values.PairProduct(predicate).Any();
}
public static void ForEachPair<T>(this IEnumerable<T> values,
Action<T, T> action)
{
foreach (Tuple<T, T> pair in values.PairProduct())
{
action(pair.Item1, pair.Item2);
}
}
public static void ForEachPair<T>(this IEnumerable<T> values,
Action<T, T> action, Func<T, T, bool> predicate)
{
foreach (Tuple<T, T> pair in values.PairProduct(predicate))
{
action(pair.Item1, pair.Item2);
}
}
public static IEnumerable<Tuple<T, T>> PairProduct<T>(
this IEnumerable<T> values)
{
return from value1 in values
from value2 in values
select Tuple.Create(value1, value2);
}
public static IEnumerable<Tuple<T, T>> PairProduct<T>(
this IEnumerable<T> values, Func<T, T, bool> predicate)
{
return from value1 in values
from value2 in values
where predicate(value1, value2)
select Tuple.Create(value1, value2);
}
public static IEnumerable<Tuple<T, T>> PairPermutations<T>(
this IEnumerable<T> values) where T : IComparable<T>
{
return from value1 in values
from value2 in values
where value1.CompareTo(value2) != 0
select Tuple.Create(value1, value2);
}
public static IEnumerable<Tuple<T, T>> PairPermutations<T>(
this IEnumerable<T> values, IComparer<T> comparer)
{
return from value1 in values
from value2 in values
where comparer.Compare(value1, value2) != 0
select Tuple.Create(value1, value2);
}
public static IEnumerable<Tuple<T, T>> PairCombinations<T>(
this IEnumerable<T> values) where T : IComparable<T>
{
return from value1 in values
from value2 in values
where value1.CompareTo(value2) < 0
select Tuple.Create(value1, value2);
}
public static IEnumerable<Tuple<T, T>> PairCombinations<T>(
this IEnumerable<T> values, IComparer<T> comparer)
{
return from value1 in values
from value2 in values
where comparer.Compare(value1, value2) < 0
select Tuple.Create(value1, value2);
}
}