user2525463
user2525463

Reputation: 93

Combobox "Select All" in linq query

I have multiple comboboxes that pass a value to a linq query. Previously I was handling it with

    if(combobox.text == "select all")
       {combobox.text = "")

And then using the StartsWith(combobox.text) method to do the comparison, I know this is wrong. Since "jim" would return "Jimmy". How do I select all when "select all" is selected?

Upvotes: 1

Views: 473

Answers (1)

lc.
lc.

Reputation: 116498

The best would be to conditionally add the query filter:

var query = dataSource.foo.AsQueryable();
//you may or may not need AsQueryable() depending on what "foo" is
//if it is not queryable, you may need AsEnumerable(), or simply nothing

if (!combobox.Text.Equals("select all"))
    query = query.Where(x => x.Equals(combobox.Text));

return query.ToList();

The "simpler" way would be to use a boolean or, but the resulting query is uglier and may or may not be translatable to SQL (if that is what you are using):

var query = dataSource.foo
    .Where(x => combobox.Text.Equals("select all") || x.Equals(combobox.Text));

Upvotes: 2

Related Questions