【问题标题】:Check if string array elements have different values检查字符串数组元素是否具有不同的值
【发布时间】:2016-07-27 13:54:47
【问题描述】:

检查字符串数组(列表)的元素是否具有不同值的最优雅方法是什么。

例如

string[] myArray = { "one", "one", "two"};

输出:

例如

string[] myArray = { "one", "two", "three" };

输出:

是的

【问题讨论】:

    标签: c# arrays string list


    【解决方案1】:
    myArray.Distinct().Count() == myArray.Length
    

    【讨论】:

    • @Habib 它将唯一项目的数量与项目的数量进行比较,这似乎回答了这个问题。
    【解决方案2】:

    怎么样

    string[] myArray = { "one", "two", "three" };
    
    bool result = myArray.Length == myArray.Distinct().Count();
    

    .Distinct() 从 List 中删除重复值 - 因此您只需比较初始数组中的项数和不同的项数。

    【讨论】:

      【解决方案3】:

      不使用 Linq 的不同方法:

      var test = new HashSet<string>();
      foreach (var str in myArray)
      {
          if (test.Contains(str)) return false;
          test.Add(str);
      }
      return true;
      

      可能在某些数据集上表现更好。

      【讨论】:

        【解决方案4】:

        虽然不是很优雅,但这是我首先想到的。

        string[] myArray = { "one", "one", "three" };
        
        bool result = myArray.Length == new HashSet<string>(myArray).Count;
        

        我有点晚了...我希望我不必指定 &lt;string&gt; 部分...

        【讨论】:

        • 我猜你的意思是myArray.ToHashSet()。奇怪的是MS没有添加这样的标准扩展方法。
        猜你喜欢
        • 2014-09-24
        • 2016-01-17
        • 2015-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-30
        • 2013-05-02
        • 2015-01-08
        相关资源
        最近更新 更多