【问题标题】:finding possible combinations linq寻找可能的组合linq
【发布时间】:2013-03-18 06:08:27
【问题描述】:

我需要在{"a", "b","c"} 之间生成所有可能的组合。

例如,输入集如{"a", "b","c"},预期输出为{"a", "b", "c" "ab", "ac", "bc", "abc"}

【问题讨论】:

标签: c# linq permutation


【解决方案1】:

听起来您正在寻找的基本上是power set 的一种形式。这是一个简单的实现(取自this site):

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];
}

请注意,感谢&lt;&lt; 运算符,您将无法将此方法用于包含超过 30 个元素的列表。我不建议尝试使用包含接近那么多元素的列表,因为在 30 个元素时,结果集将包含 230 或 1073741824 个元素。

你可以使用这个方法来得到你想要的结果

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

但是,由于幂集包含空集,这实际上将返回结果{"", "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;
}

或者更简单地说:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多