this-Me
this-Me

Reputation: 2145

LINQ assistance

I have 10 textboxes in my winform.

For performing some validation, I use the OnValidating event handler for doing some processing. For the sake of convenience I have added all these textbox controls in an IEnumerable collection.

IEnumerable<TextBox> txtBoxList;

Inside the OnValidating eventhandler, I need help with LINQ query to get all the current values of the textboxes in the form of string collection

i.e. IList<string> contentList;

Now, my requirement is to get values of the textbox(non-empty) as a string collection. I want to make use of LINQ.

This query I used, is returning me only distinct values

contentList = txtBoxList.GroupBy(t => t.Text)
                        .Where(g => !string.IsNullOrEmpty(g.Key))
                        .Select(grp => grp.Key)
                        .ToList();

i.e., if textbox1 and textbox2 is having the same content,

ex: textbox1 : "John" and textbox2 : "John" 

then it returns only one occurrence of "John".

I need your assistance to get all the values of the textbox (including duplicates) inside string collection

Awaiting response VATSAG

Upvotes: 0

Views: 85

Answers (4)

Sharan Kumar G
Sharan Kumar G

Reputation: 1

contentList = txtBoxList.GroupBy(t => t)
                        .Where(g => !string.IsNullOrEmpty(g.Key))
                        .SelectMany(grp => grp.Skip(1))
                        .ToList();

This will list all the duplicates.

Upvotes: 0

Christian Sauer
Christian Sauer

Reputation: 10899

You are grouping by the text, e. g. "john", "john", "doe", "bla" will become "john", "doe", "bla" because you are grouping identical strings.

You can simply do:

contentList = txtBoxList.Where(g => !string.IsNullOrEmpty(g))
                        .Select(t => t.Text)
                        .ToList();

Upvotes: 1

Sayse
Sayse

Reputation: 43300

If i understand correctly then you want

this.Controls.OfType<TextBox>().Where(tb => !string.IsNullOrEmpty(tb.Text))
                               .Select(tb => tb.Text);

Find all controls on your form that are textboxes, select those that arent empty, and get the text

What you may want to do though, is add textboxes to a panel first, and then find the textboxes on that panel..

panelName.Controls.OfType<TextBox>()....

Upvotes: 4

Glorfindel
Glorfindel

Reputation: 22641

Can't you just do

contentList = txtBoxList.Where(t => t.Text != null)
                        .Select(t => t.Text)
                        .ToList();

Upvotes: 1

Related Questions