1

I want to have multiple where clauses in linq but out of them only one should execute, i was trying something like this:

public JsonResult GetPost(int? id, int? tagid, DateTime? date)
{
    var ret = from data in db.Posts.Include(x => x.Tags)
                 .Include(x => x.Neighbourhood)
                 .Where((x => x.NeighbourhoodId == id) || (y => y.PostedDate == date) || third condition).ToList()

but i was unable to put second and third condition there becoz after putting dot after y, i cant see any options.

Now, out of these three, only one parameter would have value and other two would have null so, it should checks for parameter only with value.

should i write query like this, is it correct way:

if (id != null)
{
//whole query here
}
else if (tagid != null)
{
//whole query here
}
else (date != null)
{
//whole query here
}

Is it the best way to do this or something else is possible. many many thnks in advance for any suggestion.

Simon Karlsson
  • 4,090
  • 22
  • 39
duke
  • 1,816
  • 2
  • 18
  • 32
  • @krillgar sorry i missed this but there were too many answers on this topic so i was kinda lost and not get to this question – duke Feb 04 '16 at 17:09

3 Answers3

2

Something like this?

            var ret = from data in db.Posts.Include(x => x.Tags)
             .Include(x => x.Neighbourhood)
             .Where(x => x.NeighbourhoodId == (id ?? x.NeighbourhoodId) &&
                         x.<condition>  == (tagid ?? x.<condition>) &&
                         x.PostedDate == (date ?? x.PostedDate).ToList();

Or like this:

            var ret = from data in db.Posts.Include(x => x.Tags)
             .Include(x => x.Neighbourhood)
             .Where(x => id.HasValue ? x.NeighbourhoodId == id :
                            tagid.HasValue ? x.<condition> == tagid :                             
                                x.PostedDate == date).ToList();
Julia
  • 174
  • 12
1

Another option is to build your query more dynamically. I think this also makes your code more human readable, and your conditions can be more complex if needed (for example, build your query inside a loop or something). And you can use this with any other operator, like Include etc. Once your query is built, you can call ToList().

var ret = db.Posts.Include(x => x.Tags).Include(x => x.Neighbourhood);
if (id != null)
{
    ret = ret.Where((x => x.NeighbourhoodId == id);
}
else
{
    ...
}
var result = ret.ToList();
L-Four
  • 13,345
  • 9
  • 65
  • 109
0

You could use the following:

var ret = from data in db.Posts.Include(x => x.Tags)
                 .Include(x => x.Neighbourhood)
                 .Where(x => id == null || x.NeighbourhoodId == id) 
                 .Where(x => date == null || y.PostedDate == date) 
                 .ToList();

If the paramter is null, the where-clauses returns every element of the sequence. If its not null it only returns the elements which matches.

Philip W
  • 781
  • 3
  • 7