Today I have discovered that I need to use an if statement if statement inside my LINQ statement. It went something like this
Select an item from a list that holds codes for Blah objects. These objects hold two display texts for an associated code; a long text and a short text. If the long text is equal to a double quote mark, then display the short text
To clarify a little bit, I have list of objects for a drop down. The short text is displayed in the drop down from which, on select, I obtain a value which is a short hand code, ie. “SMNG” stands for “Something”. This way I can store the short hand code with the data record and store the associated information in a different table. When I need to figure out what the short or long text for “SMNG” is, I can just get it from the different table. If I need to change the wording to the short text for instance from “Something” to “Other”, I do not need to modify anything but the database table.
Ok, back to the code. A LINQ statement as far as I know does not allow you to hold the full if statement syntax. However, thankfully in C# they have included something called the Ternary Operator, or the “?:” operator combination (written as “operator” just like a “Do […] While is an “operator”) inherited from the C/C++ ways. In my case, just the statement would look something like:
longText = longText == "\"" ? c.shortText : c.longText;
Great! Now that we know the control statement that we want to return, we can do something like this:
(from c in codeList where c.code == _status select c.longText== "\"" ? c.shortText : c.longText).Single();
This LINQ returns a single item that I am looking for using my code. I could remove the “where” clause and just update them all but I decided to do it on a single basis.
Why this and not a “normal” if statement?
It has to do with how the LINQ statement sees it and the way the compiler sees it. This is not a real “If” if you will, but rather one that spits out a variable. A “normal” if statement does not return anything, its just a conditional. (Note: I am NOT saying that a ternary statement is a function, but rather a syntactical trick). In other words, to LINQ this just looks like a variable, nothing more, just as though I was passing in a normal variable. If I put a “normal” if statement in there, it has a few issues:
- If statements have no return statements, it means that the compiler cannot guarantee something will be passed back in a select or a return
- For raw LINQ, it is not syntactically convenient to implement something like a full if statements
Reguardless, if you find a way to do normal if statements in LINQ, please let me know!