-3

I have the following string with comma between in my windows form C#

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

as you see there are duplicates of Computer1 and Computer2.
How can I check those duplicates?

I tried the following but it doesn't find any duplicate.
How should I write my code?

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;
   }
}
Steve
  • 213,761
  • 22
  • 232
  • 286
Anna
  • 69
  • 1
  • 10
  • Here's something that may be helpful https://stackoverflow.com/questions/19757992/how-do-i-check-if-my-array-has-repeated-values-inside-it . Here's another way to do this as well, `var dupsExist = !arraylist.All(new HashSet().Add);` – Trevor Mar 12 '21 at 21:06
  • Please review [MCVE] guidance on posting code to make your future questions better. The code posted here *does not* demonstrate the problem at all (which you should have found yourself by simply running it). – Alexei Levenkov Mar 12 '21 at 21:20

2 Answers2

2

Your code works as expected. Not sure why you don't get the message, however you could simplify it and reduce to a single line with

if(arraylist.GroupBy(v => v).Any(v => v.Count() > 1))
    MessageBox.Show("There are duplicate computer's name");
Steve
  • 213,761
  • 22
  • 232
  • 286
0
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);



      }
Nonik
  • 645
  • 4
  • 11
  • @Steve thank you so much. Maybe I shouldn't loop inside but now it's working as expect. And thank you everybody for your response. I love you guys ! – Anna Mar 12 '21 at 21:12
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Mar 14 '21 at 08:25