I understand that the C# keyword var implies the type at compile time and therefore requires the declaration and assignment in the same place, making the following construct illegal:
var something;
if (condition)
{
something=1;
}
else
{
something = 0;
}
Even though the C# compiler could principally determine that all assignments in the current scope result in the same type, it (presently) does not and therefore generates a compile time error.
In using var with LINQ, I sometimes want to initialize my result variable slightly differently depending on program conditions. The approach I have found is to use the ?: operator, as in:
var participants = (email == null ?
(from part in db.Participant
where part.SequenceNumber == seqNr
select part)
:
(from part in db.Participant
where part.EmailAddress == email
select part));
That works well enough if I just have two possible assignments, but quickly becomes unwieldy if there are multiple possible assignments.
Is there a more elegant approach to this?
You could use
.Where(...)rather than query syntax:but personally I simply wouldn’t use
varhere – it doesn’t scale beyond 2, but this is a classic “search” pattern. I might use:This allows multiple conditions to be composed (in this case “AND”) for a more specific query. You can also do “OR” but it is slightly more complex (unless you use
Concat/Union, which is messy).