navig8tr
navig8tr

Reputation: 1844

Using a conditional if statement in a Linq query

I'm trying to write a linq query that uses an if statement.

In the code below I'm searching for matches of

n.SAU_ID = sau.SAUID where

ReportingPeriod column contains "Oct1" then FiscalYear - aprYearDiff = sau.SAUYearCode.

Else

FiscalYear - octYearDiff = sau.SAUYearCode.

My code is only giving matches for the SAUID and "Oct1".

What code is needed to implement theese statements?

    int FiscalYear = 2014;       

    List<String> addtowns = new List<string>();

    List<Stage_Reorg> reorg = _entities.Stage_Reorg.ToList();

    int aprYearDiff = 2;
    int octYearDiff = 1;

    foreach (var sau in reorg)
    {
        addtowns.AddRange(_entities.Stage_EPSSubsidySADCSDTown
        .Where(n => n.SAU_ID == sau.SAUID 
            && (n.ReportingPeriod == "Oct1" 
            ? (FiscalYear - aprYearDiff) == sau.SAUYearCode 
            : (FiscalYear - octYearDiff) == sau.SAUYearCode))
        .Select(n =>  n.TownCode ));
    }

Upvotes: 0

Views: 250

Answers (2)

Stilgar
Stilgar

Reputation: 23551

This is a bad idea anyway. Transform the condition to

(n.ReportingPeriod == "Oct1" && (FiscalYear - aprYearDiff) == sau.SAUYearCode)  
|| (n.ReportingPeriod != "Oct1" && (FiscalYear - octYearDiff) == sau.SAUYearCode)

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Here is a possible way but this probably won't work with EF. You will need to load all records into memory then perform the filtering:

addtowns.AddRange(_entities.Stage_EPSSubsidySADCSDTown
    .Where(n => { 
                   bool b = n.ReportingPeriod == "Oct1" 
                           ? (FiscalYear - aprYearDiff) == sau.SAUYearCode 
                           : (FiscalYear - octYearDiff) == sau.SAUYearCode);
                  return b && n.SAU_ID == sau.SAUID;
                 }).Select(n =>  n.TownCode ))

Upvotes: 1

Related Questions