找到可能的组合linq

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

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

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

 public IEnumerable> GetPowerSet(this IList 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个元素中,结果集将包含2 30或1073741824元素。

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

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

但是,因为幂集包括空集,这实际上将返回结果{"", "a", "b", "c", "ab", "ac", "bc", "abc"} 。 要过滤掉空字符串,请使用以下命令:

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

或者更简单:

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