Impostor
Impostor

Reputation: 2050

Shorten Code Add Dictionary with condition

I have this code:

Dictionary<string, string> items = new Dictionary<string, string>();
if(TextBox1.Text != "")
{
    items.Add(TextBox1.Name, TextBox1.Text);
}
if (TextBox2.Text != "")
{
    items.Add(TextBox2.Name, TextBox2.Text);
}
if (TextBox3.Text != "")
{
    items.Add(TextBox3.Name, TextBox3.Text);
}

It's working fine but there are about 20 TextBox items and I want to reduce redudancy. Is there a way to make this shorter?

Upvotes: 0

Views: 57

Answers (4)

Michał Turczyn
Michał Turczyn

Reputation: 37470

You can use Controls collection of a form and filter it out based on a type of a control using OfType method and then convert it to dictionary:

var tbs = this.Controls.OfType<TextBox>()
    .Where(tb => ! string.IsNullOrEmpty(tb.Text))
    .ToDictionary(tb => tb.Name, tb => tb.Text);

Upvotes: 2

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250226

You can use an array that contains all the textboxes and use Where and ToDictionary

var dic = new[] { TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 }
    .Where(t => t.Text != "")
    .ToDictionary(t => t.Name, t => t.Text);

Upvotes: 1

david
david

Reputation: 3228

Create a function for that.

public function test(TextBox text)
{
    if(text.Text != "")
    {
        items.Add(text.Name, text.Text);
    }
}

In your main function, just call this function above like this

test(TextBox1);

Upvotes: -1

Tim Schmelter
Tim Schmelter

Reputation: 460238

You could add the TextBoxes into a collection and then use LINQ:

TextBox[] allTxt = {TextBox1,TextBox12,TextBox3,...};

Dictionary<string, string> items = allTxt
    .Where(txt => !string.IsNullOrEmpty(txt.Text))
    .ToDictionary(txt => txt.Name, txt => txt.Text);

Upvotes: 5

Related Questions