如何排列 C# 元组项?

How to permute C# Tuple Items?

如何排列包含多个字符串项的元组?

因为"6"是一个很小的数字,直接写下来效率最高:

tupple1 = a,b,c
tupple2 = a,c,b
...

你无法在更短的时间内创建程序。

但是,如果您对更通用的解决方案感兴趣,请参阅 SO 上的大量链接之一,例如:Permutation algorithms in C#

恐怕要手动使用 Tuple。所以:

var tuple = new Tuple<string, string, string>("a", "b", "c");
var combination_1 = String.Concat(tuple.Item1, tuple.Item2, tuple.Item3);
var combination_2 = String.Concat(tuple.Item1, tuple.Item3, tuple.Item2);
var combination_3 = String.Concat(tuple.Item2, tuple.Item1, tuple.Item3);
var combination_4 = String.Concat(tuple.Item2, tuple.Item3, tuple.Item1);
var combination_5 = String.Concat(tuple.Item3, tuple.Item1, tuple.Item2);
var combination_6 = String.Concat(tuple.Item3, tuple.Item2, tuple.Item1);

使用修改后的 Eric Liperts 扩展方法,您可以这样做:

扩展方法:

public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
    IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };

    return sequences.Aggregate
        ( emptyProduct, (accumulator, sequence) =>
            from accseq in accumulator
            from item in sequence
            where !accseq.Contains(item)
            select accseq.Concat(new[] { item })
        );
}

用例:

var array = new string[] { "a", "b", "c", "d", "e" };
var result = Enumerable.Range(0, array.Length).Select(_ => array).CartesianProduct();

// Print results
foreach (var item in result)
    Console.WriteLine(String.Join("", item));

如果您希望获得 所有 排列,包括 "aaa""aab" 等只需删除

where !accseq.Contains(item) 来自扩展方法。