我有一个像这样的 linq 查询
var tmp = (from t in db.sometable
where (bunch of conditions)
group t by new { t.somefield} into g
select new
{
Name = g.Key.someobject.Name,
xColor = g.Sum(a => (int?)a.LineItems.Where(m => m.Product == "x" && m.Color == true)
.Sum(m => m.Quantity)),
xBW = g.Sum(a => (int?)a.LineItems.Where(m => m.Product == "x" && m.Color == false)
.Sum(m => m.Quantity))
})
现在我想优化这个查询。如果我必须写一个存储过程,我会写这样的东西:
if(a.LineItems.Product == 'x')
{
if(m.Color == true)
xColor++;
else
xBW++;
}
这样我就可以在一次扫描中获得聚合值。基本上我想优化这个查询以避免多次扫描。
最佳答案
在 Linqpad
中查看这个简单的代码片段,它按照您期望的方式在 visual studio 中运行,删除 Dump
方法调用。我为一个简单的演示简化了类结构,它只是一个 POCO
, 不是 complex type
包含另一个 list
里面
void Main()
{
var testList = Test.CreateList();
var tmp = (from t in testList
group t by new { t.Name } into g
select new
{
Name = g.Key.Name,
xColor = g.Sum(a =>
{
if (a.Product == "x" && a.Color == true)
return a.Quantity;
return 0;
}),
xBW = g.Sum(a =>
{
if (a.Product == "x" && a.Color == false)
return a.Quantity;
return 0;
})
});
tmp.Dump();
}
public class Test
{
public string Name { get; set; }
public string Product { get; set;}
public bool Color { get; set;}
public int? Quantity { get; set;}
public static List<Test> CreateList()
{
return new List<Test>()
{
new Test {Name="A",Color = true,Product="x",Quantity=5},
new Test {Name="A",Color = true,Product="x",Quantity=5},
new Test {Name="A",Color = true,Product="x",Quantity=5},
new Test {Name="B",Color = true,Product="x",Quantity=5},
new Test {Name="B",Color = true,Product="x",Quantity=5},
new Test {Name="B",Color = true,Product="x",Quantity=5}
};
}
}
但是这是否有效还有待商榷
关于c# - linq中的switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36548768/