c# - 从集合中创建独特的 double 和三胞胎

标签 c# .net collections

我有一个项目 (String) 的集合 (List)。此集合中的项目数始终介于 0 到 9 之间。

我需要从这个集合中创建成对和三元组的所有组合。 元素在双胞胎或三胞胎中的位置无关紧要。所以 {1,2} 等于 {2,1}

我怎样才能做到这一点?也许有一些通过 LINQ 执行此操作的好方法?

最佳答案

在下面的代码中,我使用 linq 生成了所有唯一的双胞胎和三胞胎。我使用字符串具有总排序这一事实。

这会生成所有 double :

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();
    }
}

应该很容易实现IEnumerable<string>上课LinkedNode ,或以其他方式将 LinkedNodes 转换为 List<string>HashSet<string> .请注意,您可以删除行 orderby a, b.Value如果顺序不重要。

关于c# - 从集合中创建独特的 double 和三胞胎,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8201390/

相关文章:

c# - 在 RichTextBox 中显示 NLog 跟踪

Java 不可变集合

java - 接口(interface)方法如何在没有主体定义的情况下执行 Java 中的功能?

java - 单例的同步(哈希)映射

c# - 动态数据显示图表 : change Y axis range

c# - 如何还原对其 MDF 和 LDF 文件使用相同命名方案的多个 SQL Server 数据库

c# - 将 foreach 循环转换为 LINQ 查询会破坏代码

c# - 使用 RegEx 仅替换引号外的字符串

c# - 如何在 C++ 中使用类 C# 的属性

c# - 如何在 C# 中确定当前关注的进程名称和版本