排列的扩展方法

时间:2013-11-13 12:12:57

标签: c# permutation

我从一个旧的SO问题得到了这个片段但是没有想法它是如何实现的。我是界面新手所以请有人帮忙吗?

我已将它放入静态类但我不知道如何调用它以便它可以生成一组排列。

public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        // Ensure that the source IEnumerable is evaluated only once
        return permutations(source.ToArray());
    }

    private static IEnumerable<IEnumerable<T>> permutations<T>(IEnumerable<T> source)
    {
        var c = source.Count();
        if (c == 1)
            yield return source;
        else
            for (int i = 0; i < c; i++)
                foreach (var p in permutations(source.Take(i).Concat(source.Skip(i + 1))))
                    yield return source.Skip(i).Take(1).Concat(p);
    }

2 个答案:

答案 0 :(得分:3)

只需获取您的IEnumerable属性(例如:listToPermutate):

var result = listToPermutate.Permutations();

您必须手动将使用添加到静态类。

答案 1 :(得分:2)

作为参考,您应该查看MSDN Extension Methods (C# Programming Guide)。 您需要将此代码放在它自己的静态类中。然后,编译器会知道将第一个方法视为Enumerable类的扩展方法,因为第一个参数是“this IEnumerable”

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyExtensions
{
  public static class EnumerableExtensions
  {

    public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> source)
    {
      if (source == null)
        throw new ArgumentNullException("source");
      // Ensure that the source IEnumerable is evaluated only once
      return permutations(source.ToArray());
    }

    private static IEnumerable<IEnumerable<T>> permutations<T>(IEnumerable<T> source)
    {
      var c = source.Count();
      if (c == 1)
        yield return source;
      else
        for (int i = 0; i < c; i++)
            foreach (var p in permutations(source.Take(i).Concat(source.Skip(i + 1))))
                yield return source.Skip(i).Take(1).Concat(p);
    }
  }
}

然后在您要使用扩展名的代码中,您需要添加“使用MyExtensions”来导入扩展方法所在的命名空间。然后就像把它叫做

var resultList = list.Permutations();

如果你正确设置了它,你甚至会在开始输入时看到Intelesense窗口中的Permutations()函数。