0

Is there a better way to have conditional where clauses in LINQ equivalent to the following?

var doGroup=false;
var doSub=true;
var query= from mydata in Data_Details
            where 
                ((doGroup && mydata.Group == "xxxx") || (doGroup==false)) &&
                ((doSub && mydata.SubGroup == "yyyy") || (doSub==false))
            select mydata;

In the code above that works it will optionally include 'Group' and 'SubGroup' depending on whether doGroup and doSub are true are false.

I know when using method syntax you can simply keep appending code to the query in separate lines but I'd prefer to keep using query syntax.

4
  • 2
    FYI, that's called query syntax. Commented Aug 21, 2018 at 16:42
  • i think you mean 'fluent' not 'fluid' Commented Aug 21, 2018 at 16:45
  • thanks I couldn't think of what linq syntax was called, and yes I did mean fluent. But what does Martin Fowler know, Fluid sounds better ;-) Commented Aug 22, 2018 at 9:59
  • I've always called it method syntax and that's what MS calls it. learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… Commented Aug 22, 2018 at 11:16

3 Answers 3

3

The easiest way to make this smaller is by optimizing the conditions themselves:

var doGroup=false;
var doSub=true;
var query=from mydata in Data_Details
                where 
                    (!doGroup || mydata.Group == "xxxx") &&
                    (!doSub || mydata.SubGroup == "yyyy")
                select mydata;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I didn't know whether there was a way to simply append to the query on multiple lines then call 'Select' as you would with the fluent interface.
0

You can write an extension method:

public static IQueryable<T> WhereIf<T>(
   this IQueryable<T> source, bool condition, 
   Expression<Func<T, bool>> predicate)
{
    if (condition)
        return source.Where(predicate);
    else
        return source;
}

Usage:

var doGroup =false;
var doSub = true;

var query = Data_Details
   .WhereIf(doGroup, q => q.Group == "xxxx")
   .WhereIf(doSub, e => e.SubGroup == "yyyy")

1 Comment

Thanks, I never knew about extension methods. I don't know why it was negged. But for my purpose I'll stick with the simpler way in this instance :)
0

Ruud Kobes answer is the right one, a small point at which there is not need to project data, last select is not needed.

var doGroup=false;
var doSub=true;
var query=from mydata in Data_Details
            where 
                (!doGroup || mydata.Group == "xxxx") &&
                (!doSub || mydata.SubGroup == "yyyy");

Comments

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.