this-Me
this-Me

Reputation: 2145

Search duplicate entries in List<TextBox> using LINQ

I have a list containing TextBox controls. Basically all this grouped inside a groupbox control.

List<TextBox> listTextBox;

I need to check for any duplicate entries within these TextBoxes whenever the groupbox validation event is invoked.

I can only think of the boring way is to loop through the list sequentially and parse the textbox value each time and find if there is more than one entry with the same value.

Can any one help me by using a Predicate to do the same operation more efficiently.

For ex:

list.Count(//predicate that gets the value for all textbox);

if the count is more than 1, Then I'm sure there are duplicate entries in the textbox.

Is there any other better way ?

Cheers VATSAG

Upvotes: 0

Views: 458

Answers (2)

Ebad Masood
Ebad Masood

Reputation: 2379

Roughly something like this may work.

var duplicates = listTextBox
        .GroupBy(i => i.Text)
        .Where(g => g.Count() > 1)
        .Select(g => new {Count = g.Count(), 
                          Name = g.Key});
    foreach (var d in duplicates)
    {
        var keyName = d.Key;

        var count = d.Count;
    }

Upvotes: 1

bit
bit

Reputation: 4487

You could use GroupBy and then filter the groups with a Count > 1 and select the Key for all such texts. I have not complied the code but this should be close enough.

var duplicateTexts=
        listTextBox.GroupBy(tb => tb.Text)
            .Where(group => group.Count() > 1)
            .Select(group => group.Key);

Upvotes: 6

Related Questions