我想在switch语句之外声明一个全局变量,结果记录可能来自两个不同的表。我怎样才能最好地实现这个目标?
var q;
Switch(petType)
{
case 1:
var q = from c in Cats
where c.Type equals == 1
select c;
break;
case 2:
var q = from d in Dogs
where d.Type equals == 1
select d;
break;
}
foreach(var r in q)
{
//Do Stuff
}
答案 0 :(得分:0)
你有" var q"在3个地方定义。仅在一个地方需要。使用对象代替下面的var
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Dog> Dogs = new List<Dog>();
List<Cat> Cats = new List<Cat>();
object q;
int petType = 1;
switch(petType)
{
case 1:
q = from c in Cats
where c.Type == 1
select c;
break;
case 2:
q = from d in Dogs
where d.Type == 1
select d;
break;
}
}
}
public class Cat
{
public int Type { get; set; }
}
public class Dog
{
public int Type { get; set; }
}
}
答案 1 :(得分:0)
详细说明@ B.K。建议,如果OP仍然不清楚。
public abstract class Animal {
public int NoOfLegs { get; set; } // example
}
public class Cat : Animal {
}
public class Dog : Animal {
}
List<Animal> q;
Switch(petType)
{
case 1:
q = from c in Cats
where c.Type equals == 1
select c;
break;
case 2:
q = from d in Dogs
where d.Type equals == 1
select d;
break;
}
foreach(var r in q)
{
//Do Stuff
}