0

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 ));
    }
4
  • you can fix the syntax but I don't think it will work with EF anyway. Commented Aug 29, 2014 at 18:24
  • .where( a => { /*some code */ return /*some bool value*/} ) Commented Aug 29, 2014 at 18:26
  • @EugenePodskal That was actually easier to read before the edit. Commented Aug 29, 2014 at 18:32
  • @DCShannon Well, I do not say that I've made some really good formatting there. Just I am a firm believer in fair use of tabs and abundant use of parentheses to make code more readable (at least for me). Overall it is a matter of taste and personal preferences, so feel free to rollback it. Commented Aug 29, 2014 at 19:04

2 Answers 2

1

This is a bad idea anyway. Transform the condition to

(n.ReportingPeriod == "Oct1" && (FiscalYear - aprYearDiff) == sau.SAUYearCode)  
|| (n.ReportingPeriod != "Oct1" && (FiscalYear - octYearDiff) == sau.SAUYearCode)
Sign up to request clarification or add additional context in comments.

2 Comments

Could elaborate on why it's a bad idea, but upvoted anyway, as this should work better and is logically equivalent.
Because declarative code is better than imperative code and this one is simpler.
1

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 ))

1 Comment

I take to long to type. but I agree completely

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.