If you're using a named type, just declare a variable with that type before the if
, but then the question would be trivial.
So I assume you're selecting an anonymous type, so you can't explicitly declare a variable with that type.
Cast by example would work here. But that doesn't feel like a good solution. Probably creating a named type is a better idea.
var myObject =Enumerable.Empty<RowType>.Select(row=>select new {columnA, columnB, columnC});
if(city == "New York City")
{
myObject= from x in MyEFTable
where x.CostOfLiving == "VERY HIGH"
select select new {columnA, columnB, columnC};
}
else
{
myObject = from x in MyEFTable
where x.CostOfLiving == "MODERATE"
select select new {columnA, columnB, columnC};
}
Or in your specific example one could project only after the conditional:
IQueryable<RowType> partialQuery;
if(city == "New York City")
partialQuery=MyEFTable.Where(x=>x.x.CostOfLiving == "VERY HIGH");
else
partialQuery=MyEFTable.Where(x=>x.x.CostOfLiving == "MODERATE");
var myObject=partialQuery.Select(x=>x.new {columnA, columnB, columnC});
Or:
Expression<Predicate<RowType>> filter;//Note that this is an Expression, not just a delegate
if(city == "New York City")
filter=x=>x.x.CostOfLiving == "VERY HIGH";
else
filter=x=>x.x.CostOfLiving == "MODERATE";
var myObject=MyEFTable.Where(filter).Select(x=>x.new {columnA, columnB, columnC});
Or even just:
string s;
if(city == "New York City")
s="VERY HIGH";
else
s="MODERATE";
var myObject=MyEFTable.Where(x=>x.CostOfLiving == s).Select(x=>x.new {columnA, columnB, columnC});
Which one is appropriate depends on how you simplified your question.