0

I want to select 2 or more fields like this: for example we have a list of some people and now they say find people who is male and live in New York
we have 2 fields in here "City" and "Sexual".

I can do it like this

private List<tblTest> GetAll(string city, string sexual)
{
    var all = (from x in db.tblTest
               where x.city == city && x.sexual == sexual
               select x).ToList();
    return all;
}

and this one is not helping:

private List<tblTest> GetAll(string city, string sexual)
{
    var all = (from x in db.tblTest
               where x.city == city || x.sexual == sexual
               select x).ToList();
    return all;
}

with "&&" I can do it but if I want to just select "City" it is not working, and I want to search like this for 14 fields and we want to search for some fields not all fields we have and we don't know which fields we want to search

What should I do?

10
  • Are you saying you want to pass in an undetermined number of filters? So it might be just city, but next time could be city and sex? Commented Nov 30, 2015 at 13:54
  • If it's based on say the variables being null maybe something like where (city == null || x.city == city) && (sexual == null || x.sexual == sexual) Commented Nov 30, 2015 at 13:56
  • 1
    You may find this answer useful. Commented Nov 30, 2015 at 13:59
  • 1
    @StephenBrickner No it wouldn't, deferred execution means it only hits the database when you materialise the query into a list or enumerate through it. Commented Nov 30, 2015 at 14:01
  • 1
    @StephenBrickner Yes, but that's easy to move to the end. Commented Nov 30, 2015 at 14:03

1 Answer 1

2

The way I do is following:

private List<tblTest> GetAll(string city, string sexual)
{
    var query = db.tblTest.AsQueryable();
    if(!string.IsNullOrEmpty(city))
    {
        query = query.Where(x => x.city == city);
    }
    if(!string.IsNullOrEmpty(sexual ))
    {
        query = query.Where(x => x.sexual == sexual );
    }
    return all.ToList();
}

It is important to call AsQueryable otherwise it might be that, if you write IEnumerable<tblTest> query = ..., the result is queried more that 1 times.

Sign up to request clarification or add additional context in comments.

1 Comment

@MichaelMairegger Thanks for editing answer hope you find it helpful and make it more useful for future readers +1 to your answer :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.