🔒 Closed Best Method to Add Items to ListBox to avoid duplication with LINQ [Tutorial 3]

Status
Not open for further replies.
Here's the best method to add listbox items.
This method will automatically detect if items is already added to listbox

quick demo:
download


CODE:
C#:
private void button1_Click(object sender, EventArgs e)
{
    //or from clipboard if you want
    foreach(var item in listBox1.SelectedItems)
    {
        AddListBoxItems(item.ToString());
    }
}

private void AddListBoxItems(string items)
{
    listBox2.BeginUpdate();
    listBox2.Items.AddRange(items.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
        .Where(x => !listBox2.Items.Cast<string>()
        .Any(item => x.Equals(item, StringComparison.InvariantCultureIgnoreCase))).ToArray());
    listBox2.EndUpdate();

    CountListBoxItems();
}
private void CountListBoxItems()
{
    lblCount.Text = listBox2.Items.Count.ToString();
}
 
Status
Not open for further replies.

About this Thread

  • 0
    Replies
  • 269
    Views
  • 1
    Participants
Last reply from:
zackmark29

Online now

Members online
968
Guests online
1,248
Total visitors
2,216

Forum statistics

Threads
2,276,188
Posts
28,968,163
Members
1,231,157
Latest member
hassano8787h
Back
Top