mirror of
https://onedev.fprog.nl/AioNet
synced 2025-12-22 00:18:37 +01:00
47 lines
1.3 KiB
C#
47 lines
1.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace AioNet.Linq
|
|
{
|
|
public static class ExtendedLinq
|
|
{
|
|
public static IEnumerable<IEnumerable<T>> Combinations<T>(
|
|
this IEnumerable<T> source,
|
|
int subsequenceLength
|
|
)
|
|
{
|
|
return source.Combinations<T>(subsequenceLength, Enumerable.Empty<T>());
|
|
}
|
|
|
|
private static IEnumerable<IEnumerable<T>> Combinations<T>(
|
|
this IEnumerable<T> source,
|
|
int subsequenceLength,
|
|
IEnumerable<T> build
|
|
)
|
|
{
|
|
if (build.Count() == subsequenceLength)
|
|
{
|
|
return new IEnumerable<T>[] { build };
|
|
}
|
|
|
|
if (!source.Any())
|
|
{
|
|
return Enumerable.Empty<IEnumerable<T>>();
|
|
}
|
|
|
|
IEnumerable<T> rest = source.Skip(1);
|
|
|
|
IEnumerable<IEnumerable<T>> combinationsSkipping = rest.Combinations(
|
|
subsequenceLength,
|
|
build
|
|
);
|
|
IEnumerable<IEnumerable<T>> combinationsTaking = rest.Combinations(
|
|
subsequenceLength,
|
|
build.Append(source.First())
|
|
);
|
|
return combinationsTaking.Concat(combinationsSkipping);
|
|
}
|
|
}
|
|
}
|