Declaring an implicitly typed variable inside conditional scope and using it outside

前端 未结 7 2155
闹比i
闹比i 2021-01-06 01:51

In the simplified code below,

if(city == \"New York City\")
{
  var MyObject = from x in MyEFTable
                     where x.CostOfLiving == \"VERY HIGH\         


        
7条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 02:06

    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.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 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> 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.

提交回复
热议问题