Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
This code works well thanks to you.
How do I prevent duplicate items in listBox1?
What should I change the code below?


C#
listBox1.Items.AddRange(textBox2.Lines.Select(l => 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());
Posted
Updated 4-Oct-16 4:37am
v2
Comments
Richard MacCutchan 4-Oct-16 9:58am    
You already have a suggestion in your original post.

try this

C#
foreach (var item in textBox2.Lines.Select(l => textBox1.Text + " " + l).ToArray())
          {
              if (!listBox1.Items.Contains(item))
                  listBox1.Items.Add(item);
          }
 
Share this answer
 
Comments
Member 10410972 4-Oct-16 11:25am    
Thanks a lot. Works great!
Karthik_Mahalingam 5-Oct-16 0:39am    
welcome :)
While Karthik's code will work, it's better to remove duplicates from the input instead:
C#
IEnumerable<string> lines = textBox2.Lines.Distinct();
listBox1.Items.AddRange(lines.Select(l => textBox1.Text + " " + l).ToArray());
 
Share this answer
 
Comments
Member 10410972 4-Oct-16 11:21am    
Thanks a lot.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900