Alex Kibler
Alex Kibler

Reputation: 4954

Trying to figure out if any of the textboxes in a collection of textboxes have duplicate values (Visual C# 2010)

I'm automatically generating text boxes on a form based on a parameter in an Oracle Database. The user enters data in the format "A14/3". I've already got code putting all of the textboxes in a collection.

var sortedTextboxes = panel1.Controls
                    .OfType<TextBox>() // get all textboxes controls
                    .OrderBy(ctrl => ctrl.Text); // order by TabIndex
foreach (TextBox txt in sortedTextboxes)
{ 
    //parse and check format
}

I need to figure out how to check for duplicates. I'm sorting by text, so all of the values will be in alphabetical order. Can I just check the current textbox's value with the previous textbox's value? If so, how can I do that?

Upvotes: 0

Views: 38

Answers (3)

tam
tam

Reputation: 1583

You could insert all the values into a hashset of strings then compare your text box collection count against the hashset collection count. If the are the same, you have no duplicates

var hash = new HashSet<string>();
foreach(var textBox in textBoxes){
    if(hash.contains(textBox.Value){
        break;

    hash.add(textBox.Vaule);
}
if(hash.Count != textBoxes.Count){
    //duplicate
}

Upvotes: 1

Pankti Jain
Pankti Jain

Reputation: 74

Change your code to save previous text box id

var sortedTextboxes = panel1.Controls
                .OfType<TextBox>() // get all textboxes controls
                .OrderBy(ctrl => ctrl.Text); // order by TabIndex

var preTextboxId=""; foreach (TextBox txt in sortedTextboxes) {

//parse and check format
if ( preTextboxId == txt.id)
{
    //duplicate
}
else
{
    add text box
}
preTextboxId = txt.id

}

Upvotes: 0

Habib
Habib

Reputation: 223287

You can get duplicate textboxes and their content if you group your results based on Text and then get only those items whose count is greater than 1. Like:

var sortedTextboxes = panel1.Controls
                    .OfType<TextBox>() // get all textboxes controls
                    .GroupBy(r => r.Text)
                    .Where(grp=> grp.Count() > 1)
                    .Select(grp => new
                    {
                        DuplicateText = grp.Key,
                        DuplicateTextBoxes = grp.Select(r => r).ToList(),
                    });

Upvotes: 1

Related Questions