c# - 寻找可能的组合 linq

标签 c# linq permutation

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

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

最佳答案

听起来您要找的基本上是 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];
}

请注意,感谢 <<运算符,您将无法将此方法用于包含超过 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);
}

关于c# - 寻找可能的组合 linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15470672/

相关文章:

c# - Selenium Nunit 插件安装异常

c# - LINQ To SQL、C#、MVC 4、模型助手中的连接问题

c - 将整数数组映射到字符串数组时如何进行排列?

python - 具有重叠值的列表的排列

java - 找出足球锦标赛中所有比赛的所有可能结果

c# - 从数组中删除重复项

c# - NAudio WasapiLoopbackCapture ComException(0x88890003)

c# - 何时使用 Literal 与 LiteralControl?

json - 如何使用 LINQ 查询此 JSON 字符串?

c# - 如何迭代子列表中的元素,然后从列表中删除子列表?性能卓越