这是我的代码:
var query = from x in Data
select new { Fruit = x[0], Animal, x[2], Color = x[3], Food = x[4] };
现在,我想创建一个复选框,这样如果用户勾选“方框1”,它将执行不同的查询,如下所示:
select new { Fruit = x[7], Animal, x[4], Color = x[8], Food = x[9] };
我的问题是,如何制作,以便根据选中的复选框使用不同的select...new
语句?
我想我可以使用多个if / then语句来查看选中哪个特定的框并确定要使用哪个select...new
语句,但我猜测有更好的方法。
在VB中我认为一个“案例”陈述会发挥作用,但我不知道C#等价物是什么。
我在更改查询参数的上下文中尝试实现case / switch失败了:
int caseSwitch = 1;
var query = from x in Data
switch (caseSwitch)
{
case 1:
select new { Fruit = x[0], Animal, x[2], Color = x[3], Food = x[4] };
break;
case 2:
select new { Fruit = x[7], Animal, x[4], Color = x[8], Food = x[9] };
break;
}
答案 0 :(得分:1)
您可以将选择项分解为函数:
function object getItem(DataItem x, int caseSwitch)
{
switch (caseSwitch)
{
case 1:
return new { Fruit = x[0], Animal, x[2], Color = x[3], Food = x[4] };
break;
case 2:
return new { Fruit = x[7], Animal, x[4], Color = x[8], Food = x[9] };
break;
}
}
然后您可以执行以下查询:
int caseSwitch = 1;
var query = from x in Data
select getItem(x, caseSwitch);
答案 1 :(得分:1)
为了改变您的查询,您可以使用switch
语句。但是,这样做不能使用匿名类型。您需要定义一个可以使用的对象,因此可以在声明时定义查询对象。
public class Foo
{
public string Fruit { get; set; }
public string Animal { get; set; }
public string Color { get; set; }
public string Food { get; set; }
}
IEnumerable<Foo> query = null;
switch (caseSwitch)
{
case 1:
query = from x in Data
select new Foo { Fruit = x[0], Animal = x[2], Color = x[3],
Food = x[4] };
break;
case 2:
query = from x in Data
select new Foo { Fruit = x[7], Animal = x[4], Color = x[8],
Food = x[9] };
break;
default:
// handle however you need to
}
您也可以将其完全内联到LINQ查询中,但是,如果扩展多个案例的代码会使代码更难以理解和维护。
var query = from x in Data
// needed to get the caseSwitch value into context in the select
// otherwise it is considered out of context
let sw = caseSwitch
select sw == 1 ?
new { Fruit = x[0], Animal = x[2], Color = x[3], Food = x[4] } :
new { Fruit = x[7], Animal = x[4], Color = x[8], Food = x[9] }
这种方法的问题是当caseSwitch
超出有效值范围时,您可能会得到一个您不想要的值。使用switch
语句可以更好地处理这种情况,您可以将查询设置为默认值,或者在达到default
的情况下抛出异常。
有两个以上情况的内联LINQ的示例
var query = from x in Data
let sw = caseSwitch
select
sw == 1 ? new { Fruit = x[0], Animal = x[2], Color = x[3], Food = x[4] }
: sw == 2 ? new { Fruit = x[7], Animal = x[4], Color = x[8], Food = x[9] }
: sw == 3 ? new { Fruit = x[10], Animal = x[11], Color = x[12], Food = x[13] }
: null; // final value is the default value