如何检查字符串数组c#中的重复项 [英] How to check duplicates in string array c#

查看:89
本文介绍了如何检查字符串数组c#中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字符串数组c#中的重复项。如果重复存在,也会显示一条消息....

解决方案

您可以使用 Distinct 方法。类似于:

  string  [] myStrings =  //   ...  

if (myStrings .Distinct()。Count()!= myStrings.Count())
{
// 显示消息
}


有几个选项。一种方法是:

  • 首先对数组进行排序。
  • 然后,foreach项:如果它等于下一项,那么你有一个副本(和你可以显示消息)。


你可以使用Distinct()作为Shmuel提到的。

如果你想显示重复的项目,然后你可以使用Linq

  string  [] array = { 首先 第二个 第三个  首先 第三个}; 
var i = CheckforDuplicates(array);





< pre lang =c#> public bool CheckforDuplicates( string [] array)
{
var duplicates = array
.GroupBy(p = > p)
。其中(g = > g.Count()> 1
。选择(g = > g 。键);


return (duplicates.Count()> < span class =code-digit> 0 );



}





其中变量重复包含重复项目清单


How to check duplicates in string array c#..Also show a message if duplicate present....

解决方案

You can use the Distinct method. Something like:

string[] myStrings = // ...

if (myStrings.Distinct().Count() != myStrings.Count())
{
    // Show message
}


There are several options. One method is:
  • First sort the array.
  • Then, foreach item: if it is equal to the next one then you have a duplicate (and you may show the message).


You can use Distinct() as Shmuel mentioned.
If you want to display the duplicated items , then you can use Linq

 string[] array = { "First", "Second", "Third", "First", "Third" }; 
var i= CheckforDuplicates(array);



public bool CheckforDuplicates(string[] array)
      {
          var duplicates = array
           .GroupBy(p => p)
           .Where(g => g.Count() > 1)
           .Select(g => g.Key);


          return (duplicates.Count() > 0);



      }



where the variable duplicates contains the list of repeated items


这篇关于如何检查字符串数组c#中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆