如何防止listbox1中的重复项? C# [英] How do I prevent duplicate items in listbox1? C#
本文介绍了如何防止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());
推荐答案
试试这个< br $>
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());
这篇关于如何防止listbox1中的重复项? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文