找到可能的组合linq

ser*_*ene 3 c# linq permutation

我需要生成所有可能的组合{"a", "b","c"}.

例如,输入集就像{"a", "b","c"}预期输出一样{"a", "b", "c" "ab", "ac", "bc", "abc"}.

p.s*_*w.g 10

听起来你正在寻找的基本上是一种动力装置.这是一个简单的实现(取自本网站):

public IEnumerable<IEnumerable<T>> GetPowerSet<T>(this IList<T> list)
{
    return from m in Enumerable.Range(0, 1 << list.Count)
           select
               from i in Enumerable.Range(0, list.Count)
               where (m & (1 << i)) != 0
               select list[i];
}
Run Code Online (Sandbox Code Playgroud)

请注意,由于<<运算符,您将无法将此方法用于包含30个以上元素的列表.我不建议尝试使用接近那么多元素的列表,因为在30个元素中,结果集将包含2 30或1073741824元素.

您可以使用此方法获得您想要的结果

public IEnumerable<string> GetPermutations(IList<string> strings)
{
    return from s in strings.GetPowerSet()
           select string.Concat(s);
}
Run Code Online (Sandbox Code Playgroud)

但是,由于幂集包含空集,因此实际上会返回结果{"", "a", "b", "c", "ab", "ac", "bc", "abc"}.要过滤掉空字符串,请使用以下命令:

public IEnumerable<string> GetPermutations(IList<string> strings)
{
    return from s in strings.GetPowerSet()
           let str = string.Concat(s)
           where str.Length > 0 // exclude null set result
           select str;
}
Run Code Online (Sandbox Code Playgroud)

或者更简单:

public IEnumerable<string> GetPermutations(IList<string> strings)
{
    return from s in strings.GetPowerSet().Skip(1)
           select string.Concat(s);
}
Run Code Online (Sandbox Code Playgroud)