Learner
Learner

Reputation: 4004

How to add conditional condition to LINQ query based on a previously returned value

For example:

var sList = from ASL in aslist
            where ASL.Description == as.ToString()
            select ASL;
as = sList.FirstOrDefault();
var rList = from ARL in arlist
            where ARL.Description == rDescription && ARL.Id == as.Id
            select ARL;

Now as you see, the last condition of rList query (i.e. && ARL.Id == as.Id) is based on the value retrieved from sList query. My problem is when sList is NULL, I get an error. I want to include last condition (i.e. && ARL.Id == as.Id) only if sList is not null.

I can do it using if else like as shown below, but I want to do it elegantly using LINQ if possible:

if (as != null)
{
    // include ARL.Id == as.Id condition in the query
} 
else
{
    // exclude ARL.Id == as.Id condition from the query
}

Thanks in advance!

Upvotes: 2

Views: 4566

Answers (2)

Jeremy Todd
Jeremy Todd

Reputation: 3289

Depending on what query provider you're using, I'd probably recommend not including the condition in your LINQ query at all if you can determine in advance that it doesn't belong there. It probably won't make much of a difference if you're using LINQ to Objects, but if you're using LINQ to SQL or LINQ to Entities, including extraneous conditions in your query might cause the query provider to generate SQL code with unnecessary joins that could affect performance, or maybe not even work at all if the provider doesn't understand the code you're using to test for missing values.

I'd do something like:

var sList = from ASL in assetsensorlist
            where ASL.Description == assetSensor.ToString()
            select ASL;
assetsensor = sList.FirstOrDefault();

var rList = from ARL in assetruleslist
            where ARL.Description == ruleDescription
            select ARL;

if (assentsensor != null)
{
  // Fluent syntax is simpler for this purpose
  rList = rList.Where(x => x.SensorID == assetsensor.ID);
}

Upvotes: 0

Darko Kenda
Darko Kenda

Reputation: 4960

&& (assetsensor == null || ARL.SensorID == assetsensor.ID)

Upvotes: 6

Related Questions