【问题标题】:How do I check if a list contains a tuple in C#如何检查列表是否包含 C# 中的元组
【发布时间】:2022-12-06 21:15:53
【问题描述】:

在添加新元组之前,我想检查列表是否已经包含该元组并避免再次将其添加到列表中,我该怎么做呢?我知道对于整数和字符串,您只需编写 list.Contains(2) 或 list.Contains("2"),但我不确定在检查元组时使用什么语法。

到目前为止,我已经尝试过这两个 (sn-ps)。 (组合是一个元组列表<char, char>)

if(!combinations.Contains(Tuple<char, char>(s[i], chr)))
{
    combinations.Add(new Tuple<char, char>(s[i], chr));
}
                    
if(!combinations.Contains(Tuple<char, char> s[i], chr))
{
    combinations.Add(new Tuple<char, char>(s[i], chr));
}

添加效果很好,所以我认为比较时会相同。任何有关语法或逻辑的帮助都会很棒,谢谢 :)

【问题讨论】:

  • 您可以使用.Contains(Tuple.Create(s[i], chr))。另外:如果你的combinationsList&lt;Tuple&lt;char, char&gt;&gt;并且你不想重复,也许你想改用HashSet&lt;Tuple&lt;char, char&gt;&gt;?如果条目已经在集合中,它的 Add 方法将不执行任何操作。
  • 我假设您想知道元组是否具有与列表中已有值相同的值?而不是实际上是同一个元组(相同的内存地址)?

标签: c# list tuples


【解决方案1】:

在 C# 中,您可以使用 Contains() 方法来检查列表是否包含特定元组。这是一个例子:

// List of tuples
var tupleList = new List<(char, char)>()
{
    ('a', 'b'),
    ('c', 'd'),
    ('e', 'f')
};

// Tuple to search for
var searchTuple = ('a', 'b');

// Check if the list contains the tuple
if (tupleList.Contains(searchTuple))
{
    Console.WriteLine("The list contains the tuple");
}
else
{
    Console.WriteLine("The list does not contain the tuple");
}

【讨论】:

    【解决方案2】:

    元组已经实现了适当的相等性,因此您不需要做任何事情,只需创建值,然后使用.Contains。然而:

    1. 你可能更喜欢ValueTuple&lt;...&gt;而不是Tuple&lt;...&gt;,并且
    2. 如果顺序不重要,您可能更喜欢HashSet&lt;T&gt;,它在内部处理唯一性

      例如:

      // note that (char, char) is a ValueTuple<char, char>
      private readonly HashSet<(char,char)> combinations = new();
      //...
      combinations.Add((x, y)); // adds the x/y tuple if it doesn't exist
      

      你也可以姓名这里的部分:

      private readonly HashSet<(char X,char Y)> combinations = new();
      

      这将允许您通过编译器 voodoo 在值上使用 .X.Y

    【讨论】:

      【解决方案3】:

      这是您的解决方案

      List<Tuple<char, char>> combinations = new() {
                   new Tuple<char, char>('A', 'B'),
                   new Tuple<char, char>('C', 'D'),
                   new Tuple<char, char>('E', 'F')
                   };
      
      // 
      var t1 = new Tuple<char, char>('A', 'B');
      //you can perform ||(OR) or &&(AND) in between item1 and item2
      bool isExist = combinations.Any(x => x.Item1 == t1.Item1 || x.Item2 == t1.Item2); 
      
      

      Any 是一个 linq 扩展方法 supporting docs

      【讨论】:

        猜你喜欢
        • 2019-12-01
        • 1970-01-01
        • 2014-04-30
        • 2016-05-12
        • 2012-03-26
        • 2020-10-22
        • 1970-01-01
        • 2012-08-14
        • 2021-06-24
        相关资源
        最近更新 更多