如何防止listbox1中的重复项? C#

问题描述:

This code works well thanks to you.
How do I prevent duplicate items in listBox1?
What should I change the code below?







listBox1.Items.AddRange(textBox2.Lines.Select(l => textBox1.Text + " " + l).ToArray());





我尝试过:



类似于:

listBox1.Items.AddRange(textBox2.Lines.Select(l => textBox1.Text +) + l)&&!listBox1.Items.Contains(textBox1.Text ++ l))。ToArray());



What I have tried:

Something like:
listBox1.Items.AddRange(textBox2.Lines.Select(l => textBox1.Text + " " + l) && !listBox1.Items.Contains(textBox1.Text + " " + l)).ToArray());

试试这个


try this

foreach (var item in textBox2.Lines.Select(l => textBox1.Text + " " + l).ToArray())
          {
              if (!listBox1.Items.Contains(item))
                  listBox1.Items.Add(item);
          }


虽然Karthik的代码可以使用,但最好从输入中删除重复项:

While Karthik's code will work, it's better to remove duplicates from the input instead:
IEnumerable<string> lines = textBox2.Lines.Distinct();
listBox1.Items.AddRange(lines.Select(l => textBox1.Text + " " + l).ToArray());