在下面的代码中,我使用 linq 生成了所有唯一的双胞胎和三胞胎。我使用字符串具有总排序的事实。
这会生成所有双打:
string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
var combinations =
from a in items
from b in items
where a.CompareTo(b) < 0
orderby a, b
select new { A = a, B = b };
foreach(var pair in combinations)
Console.WriteLine("({0}, {1})", pair.A, pair.B);
这会生成所有三元组:
string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
var combinations =
from a in items
from b in items
from c in items
where a.CompareTo(b) < 0 && b.CompareTo(c) < 0
orderby a, b, c
select new { A = a, B = b, C = c };
foreach(var triplet in combinations)
Console.WriteLine("({0}, {1}, {2})", triplet.A, triplet.B, triplet.C);
更新:有一个通用的解决方案来创建特定长度的所有唯一子集,并且仍然使用 linq。但是,您需要一个可以包含子集的返回类型。我创建了一个简单的类LinkedNode,因为对我来说这与 linq 结合起来感觉最自然:
void Main()
{
string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
foreach(var combination in CreateCombinations(items, 5))
Console.WriteLine("({0})", combination.ToString());
}
private static IEnumerable<LinkedNode> CreateCombinations(string[] items, int length)
{
if(length == 1)
return items.Select(item => new LinkedNode { Value = item, Next = null });
return from a in items
from b in CreateCombinations(items, length - 1)
where a.CompareTo(b.Value) < 0
orderby a, b.Value
select new LinkedNode<T> { Value = a, Next = b };
}
public class LinkedNode
{
public string Value { get; set; }
public LinkedNode Next { get; set; }
public override string ToString()
{
return (this.Next == null) ? Value : Value + ", " + Next.ToString();
}
}
在LinkedNode 类上实现IEnumerable<string> 应该很容易,或者将LinkedNodes 转换为List<string> 或HashSet<string>。请注意,如果顺序不重要,您可以删除行 orderby a, b.Value。