听起来您正在寻找的基本上是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);
}