简体   繁体   中英

How to use var more than once in linq?


var ID, x,y

switch(ItemTypeNo)
{

   case ItemType.A : 

    ID = from s in cntx.Tablo1
break;


   case ItemType.B : 

    ID = from s in cntx.Tablo2
break;


   case ItemType.C : 

    ID = from s in cntx.Tablo3
break;

}

You can only use var for inline initialization, which that isn't. You would need to type ID appropriately, and since var has a single type that would only work if Tablo1 , Tablo2 and Tablo3 are the same type (which seems unlikely).

What is it you need to do here?

There is a scenario that works here; when selecting a common type from each; let's assume thay all have an int primary key:

IQueryable<int> ids;    
switch(ItemTypeNo)
{    
   case ItemType.A : ids= from s in cntx.Tablo1 select s.Id; break;
   case ItemType.B : ids= from s in cntx.Tablo2 select s.Id; break;
   case ItemType.C : ids= from s in cntx.Tablo3 select s.Id; break;
   default: throw new InvalidOperationException();
}

However, in the general case... not so much. You could type ID as the non-generic IQueryable , but to be honest that doesn't let you do very many interesting things. And dynamic doesn't play nicely with LINQ (and even if it did, it would be a hack here).

The anonymous type "var" can not be declared without having it initialized. Once "var" is initialized (once it is inferred from usage), it can't be altered throughout the course of its lifetime.

您可以将ID声明为IQueryable因为这是通用IQueryable<T>基本类型

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM