c# linq 实现 m选n 组合

void Main()
{
    var result = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.DifferentCombinations(3);
    result.Dump();
}

public static class Ex
{
    public static IEnumerable<IEnumerable<T>> DifferentCombinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).DifferentCombinations(k - 1).Select(c => (new[] { e }).Concat(c)));
    }
}
// Define other methods and classes here

 

posted on 2020-04-24 14:24  空明流光  阅读(353)  评论(0编辑  收藏  举报

导航