Using anonymous types - how to avoid a lot of code

advertisements

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:

// Same anonymous type properties and types as later:
var variable = Enumerable.Repeat(0, new { ... });

if (condition) {
    variable = ...;
} else {
    variable = ...;
}

Alternatively, you could use the conditional operator:

var variable = condition ? ... first query ...
                         : ... second query ...

Thirdly, you could build the query up using composition instead. For example, if the only difference is the ordering, you could do:

var firstPart = ...;

var secondPart = condition ? query.OrderBy(...) : query.OrderByDescending(...);

var query = secondPart.Select(...);

EDIT: Now you've given an example, we can make this concrete:

string username = membership.GetUser(cANDu[1]).ProviderUserKey.ToString();
var query = objDC.tickets
                 .Where(el => el.typeOfGame == cANDu[0] &&
                              el.username == username);

if (condition)
{
    query = query.Where(el => el.results != null);
}

var result = query.Select(el => new { el.AllGamesTickets, el.WGamesTickets})
                  .FirstOrDefault();