可能重复:
linq case statement
请考虑这种情况:
我有这样的功能:
private void MyFunction(byte Period)
{
...
我在数据库中有一个表格,如下所示:
... F008 F009_1 F009_2 F009_3 F009_4 F009_5 F009_6 F009_7 F009_8 ...
-------------------------------------------------------------------------------------------------
在函数体中我想做一些计算。
var MyCalculation = from r in ent.MyTable
group r by new { r.F000 } into grp
select new
{
F008 = grp.Sum(o => o.F008)
F009 = ?????
问题出现在F009
我应该在linq投影中做到这一点:
switch(Period)
{
case 1:
F009 = (Sum of F009_1) + (Sum of F009_2);
break;
case 2:
F009 = (Sum of F009_3) + (Sum of F009_4);
break;
case 3:
F009 = (Sum of F009_5) + (Sum of F009_6);
break;
case 4:
F009 = (Sum of F009_7) + (Sum of F009_8);
break;
}
如何在linq投影中使用此switch case
?
感谢
答案 0 :(得分:0)
它应该像内联和连接查询组合。 请告诉确切的情况或您撰写的查询。
您可以遵循的一种方法是,构建查询并编写switch case并在其中包含您的查询。 等,
case 1: var MyCalculation = from r in ent.MyTable
group r by new { r.F000 } into grp
select new
{
F008 = grp.Sum(o => o.F008)
F009 =F009_1+F009_2,}
` 像这样可以做类似的方式..反正查询将执行一次,是最简单的方法
答案 1 :(得分:0)
var groupQuery = ent.MyTable.GroupBy(r => r.F0000 );
IEnumerable<Result> query;
switch(Period)
{
case 1:
query = groupQuery.Select(grp => new Result {
F008 = grp.Sum(r => r.F008),
F009 = grp.Sum(r => r.F009_1 + r.F009_2)
};
break;
case 2:
query = groupQuery.Select(grp => new Result {
F008 = grp.Sum(r => r.F008),
F009 = grp.Sum(r => r.F009_3 + r.F009_4)
};
break;
case 3:
query = groupQuery.Select(grp => new Result {
F008 = grp.Sum(r => r.F008),
F009 = grp.Sum(r => r.F009_5 + r.F009_6)
};
break;
case 4:
query = groupQuery.Select(grp => new Result {
F008 = grp.Sum(r => r.F008),
F009 = grp.Sum(r => r.F009_7 + r.F009_8)
};
break;
}
var MyCalculation = query.ToList();
你的DTO:
public class Result
{
// provide actual data types
public int F008 { get; set; }
public int F009 { get; set; }
}