These extension methods will allow you to list all possible pairs (following the same names / conventions outlined in the older SO python question you are associated with), and also provides the requested AnyPair and ForEachPair methods.
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); } }
source share