🔒 Closed Best Method to Add Items to ListBox with RegEx using LINQ [Tutorial 4]

Status
Not open for further replies.
This is the best method (for me) to avoid adding duplicate items and with match of your regular E×ρréššion

quick demo:
download



CODE:

C#:
private void button1_Click(object sender, EventArgs e)
{
    Regex httpRegEx= new Regex(@"(https.+|http.+)[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
  
    foreach (var item in listBox1.SelectedItems)
    {
        AddListBoxItemsWithRegEx(item.ToString(), httpRegEx);
    }
}
private void AddListBoxItemsWithRegEx(string input, Regex pattern)
{
    var newItems = pattern.Matches(input).Cast<Match>()
        .Where(m => !listBox2.Items.Cast<string>()
        .Any(item => item.Equals(m.Value, StringComparison.InvariantCultureIgnoreCase)))
        .Select(m => m.Value).ToArray();
    
    if (newItems.Any())
    {
        listBox2.BeginUpdate();
        foreach (var item in newItems) {
            listBox2.Items.Add(item);
        }
        listBox2.SelectedIndex = listBox2.Items.Count - 1;
        listBox2.EndUpdate();
    }

    CountListBoxItems();
}

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

About this Thread

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

Online now

Members online
967
Guests online
2,450
Total visitors
3,417

Forum statistics

Threads
2,276,141
Posts
28,967,846
Members
1,231,131
Latest member
Yrrojan
Back
Top