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.
x.*
you mean the construction of an anonymous type, right? If not, why are you insisting on implicit typing? – Bigotedselect new {columnA, columnB, columnC}
. Sorry for oversimplification. – Appetizerwhere
clause of the LINQ query, you can avoid the whole issue: eliminate theif
block and change thewhere
clause towhere x.CostOfLiving == ((city == "New York City") ? "VERY HIGH" : "MODERATE")
. In a more-complex case, replace thewhere
clause with an appropriate generic predicate... – EterneWHERE
will be absent in myelse
part. Instead of editing the code, I'm leaving it for context. In any case, Eric's suggestion worked for me. Thank you SOF. – Appetizer