【问题标题】:How to check duplicates in string array in C# windows form [duplicate]如何在 C# windows 窗体中检查字符串数组中的重复项[重复]
【发布时间】:2021-06-10 21:27:30
【问题描述】:

我的 Windows 窗体 C# 中有以下带逗号的字符串

string computernames = "Computer1,Computer2,Computer3,Computer2,Computer1";

如您所见,Computer1 和 Computer2 存在重复项。
如何检查这些重复项?

我尝试了以下方法,但没有找到任何重复项。
我应该如何编写我的代码?

string[] arraylist =  computernames.Split(',');
var groups = arraylist.GroupBy(v => v);
foreach (var item in groups)
{
    if(item.Count() > 1)
    {
       MessageBox.Show("There is dubblication of computer name");
       return;
   }
}

【问题讨论】:

  • 这里有一些可能有用的东西stackoverflow.com/questions/19757992/…。这也是另一种方法,var dupsExist = !arraylist.All(new HashSet<string>().Add);
  • 请查看minimal reproducible example 发布代码的指南,以便更好地解决您未来的问题。此处发布的代码根本没有说明问题(您应该只需运行它就可以发现)。

标签: c# arrays list winforms


【解决方案1】:

您的代码按预期工作。不知道为什么您没有收到该消息,但是您可以将其简化并减少为一行

if(arraylist.GroupBy(v => v).Any(v => v.Count() > 1))
    MessageBox.Show("There are duplicate computer's name");

【讨论】:

    【解决方案2】:
    public static bool CheckfrDuplicates(string[] array)
          {
              var duplicates = array
               .GroupBy(p => p)
               .Where(g => g.Count() > 1)
               .Select(g => g.Key);
    
    
              return (duplicates.Count() > 0);
    
    
    
          }
    

    【讨论】:

    • @Steve 非常感谢。也许我不应该在里面循环,但现在它按预期工作。谢谢大家的回复。我爱你们!
    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多