I have this situation:
if (condition){
var variable = (from el in ....) //linq to sql query
}
else{
var variable = (from el in ....) //linq to sql query
}
// code where i can`t use the variable
I want to avoid copying code in both conditions.
var getHistoryTips = (from el in objDC.tickets
where el.typeOfGame == cANDu[0]
&& el.username == Membership.GetUser(cANDu[1]).ProviderUserKey.ToString()
select new { el.AllGamesTickets, el.WGamesTickets}).FirstOrDefault();
var getHistoryTips = (from el in objDC.tickets
where el.typeOfGame == cANDu[0]
&& el.results != null
&& el.username == Membership.GetUser(cANDu[1]).ProviderUserKey.ToString()
select new { el.AllGamesTickets, el.WGamesTickets}).FirstOrDefault();
Three options:
Firstly, you can use an “example” – to type the variable:
Alternatively, you could use the conditional operator:
Thirdly, you could build the query up using composition instead. For example, if the only difference is the ordering, you could do:
EDIT: Now you’ve given an example, we can make this concrete: