3

I have a linq statement that I want to add an additional where clause to if a drop down index is not 0.

people.Where(n.surname == "surname" || n.forename == "forename" && (dropdown.SelectedIndex > 0) ? n.id = dropdown.SelectedValue : n.id  > 0).Select(n => n);

I am not even sure if what I am trying is possible??

I would like to do this rather than having to write two different statements.

Any ideas?

Thanks

1 Answer 1

11

Fortunately, this is easy because queries compose:

var query = people.Where(n.surname == "surname" || n.forename == "forename");
if (dropdown.SelectedIndex > 0)
{
    query = query.Where(n => n.id.ToString() == dropdown.SelectedValue);
}
6
  • Looks like id is an integer, but the SelectedValue property is a string. One or the other will need to be converted.
    – tvanfosson
    Commented Jun 3, 2009 at 14:38
  • getting an error "cannot be inferred from usage error in my the if statement query = query?? Commented Jun 3, 2009 at 14:48
  • I needed paramater in the where query = query.Where(n => n.id == dropdown.SelectedValue); Thanks guys Commented Jun 3, 2009 at 14:52
  • 1
    Don't you love this feature? It's like dynamic SQL but with less evil :) Commented Jun 3, 2009 at 14:55
  • (Fixed both errors in the answer. Love to know what the downvote is for.)
    – Jon Skeet
    Commented Jun 3, 2009 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.