Good afternoon, such a question. There is an array of file paths and it is necessary that no duplicate lines are added to the listbox. How can this be implemented?

  • Do not add. Check ListBox1.Items.FindByText or ListBox1.Items.FindByValue before doing Add - nick_n_a
  • Are you using WPF or WinForms ? - user227049

2 answers 2

In order to avoid duplication, you must first accumulate information in HashSet

 HashSet<string> set; List<string> list; 

Option 1 for a small number of lines

 if (!list.Contains("новая строка")) list.Add("новая строка"); 

Option 2 for everything else

 if (set.Add("новая строка")) list.Add("новая строка"); 
  • Is there an example of some kind? - Jeron
  • @Jeron Give an example of how you fill your ListBox - nick_n_a
  • foreach (ex in file) {listbox1.Items.Add (ex); } - Jeron
 var dict = arr.Where(str => arr.Count(st => st == str) > 1).Distinct() 

UPD: var dict = arr.Distinct ()

  • This may and nothing, as an example of using Linq, but there is no worse readable code and more difficult to follow than Linq. Yes, and performance is not all OK. - Zverev Evgeniy
  • Nevertheless, I would solve the problem with this design. Here the author asked a question about performance or maintainability? Maybe he has a problem in a class and a half to fit, why write a coaster with a code? Well, if they commented, then argue. - Valery Gorbunov
  • Something I do not understand how this code relates to the issue. Because, as I understand it, you just need arr.Distinct() . And that already in the comments said that does not fit. - Qwertiy
  • "There is an array of file paths" - I would filter out duplicates and calmly fill them with a box. About arr.Distinct () I agree, here blunted. But why not a solution? Or is there a contest for the wittiest comment? - Valery Gorbunov
  • one
    @ ValeryGorbunov - such a competition is going on here permanently :) - Igor