score:3

Accepted answer

the var keyword is irrelevant. you can do it like this:

switch(flag)
{
    case 1: {
              var query=from w in db.sometable
                    select w;
          }
          break;
    case 2: {
              var query=from w in db.sometable
                    where w.id==someid
                    select w;
          }
          break;
    default:
          break;
}

it is correct syntax, but i would suggest you to extract each case to each method instead.

score:0

if it is same table , you can try this:

var query=from w in db.sometable select w;
switch(flag)
{
    case 1: 
          break;
    case 2:
          query=query.where(w.id==someid); 
          break;
    default:
          query=null; //since linq is delay query, if you don't use the data in query, it will do nothing.
          break;
}

score:5

declaring with var lets you shorten the code, but the variable that you declare remains statically typed, and the scope of that variable does not change.

if you need to use a variable outside switch, declare it before the switch statement, like this:

iqueryable<sometype> query = null;
switch (...) {
    case 1: query = ...; break;
    ...
    default: ...
}

now you can use query outside the switch.

note: there are cases where you must use var because the type that you assign to it has no name, but in your first case the type has a name, so you do not need to use var.

edit : your second case, however, does require a var, because you are selecting an anonymous type. in situations like that there are several ways around this problem:

  • you can declare a named type for the "superset" of columns that you select (i.e. timetm, temperature, and radiation), or
  • in .net 4.0 you can use iqueryable<dynamic>. this shifts some of compile-time checking into runtime, but if you have to go this route, it is very convenient.

Related Query

More Query from same tag