【发布时间】:2019-06-15 16:42:29
【问题描述】:
我有一个使用 let 语句的 Linq 查询,我从中派生了几个子查询。目前,我正在做 3 个子查询来使用 3 个相同的连接来派生计数,我希望将它们组合成一个只有一个连接的子查询。我有这样的事情:
let TheFruits = (complex query).ToList(),
Counter1 = (from TheTable in MyDC.SomeTable
join x in Thefruits on
TheTable.FruitID equals x.FruitID
where x.Field1 == 1
select x).Count(),
Counter2 = (from TheTable in MyDC.SomeTable
join x in Thefruits on
TheTable.FruitID equals x.FruitID
where x.Field2 == 2
select x).Count(),
Counter3 = (from TheTable in MyDC.SomeTable
join x in Thefruits on
TheTable.FruitID equals x.FruitID
where x.Field3 == 3
select x).Count(),
为了替换 3 个连接,我想写这样的东西,但我没有在对象属性中获取扩展方法:
let TheFruits = (complex query).ToList(),
TheCounterObject = (from TheTable in MyDC.SomeTable
join x in Thefruits on
TheTable.FruitID equals x.FruitID
select new CounterObject()
{
Count1 = x.Where....Count(),
Count2 = x.Where....Count(),
Count3 = x.Where....Count(),
//not getting .Where extension
}).Single()
问题是我没有得到扩展方法,只有表格列。在我提供的简单示例中,.Where 子句仅匹配一个条件,但在我的实际子查询中,涉及 DateTimes 和其他条件。
如何在对象映射阶段运行计数?
编辑
经过更多的努力,我现在有了以下内容:
let TheFruits = (complex query).ToList(),
TheCounterObject = (from TheTable in MyDC.SomeTable
join x in TheFruits on
TheTable.FruitID equals x.FruitID
into TheSubFruits
select new CounterObject()
{
Count1 = TheSubFruits.Where(x.FruitID == TheTable.FruitID && other conditions).Count(),
Count2 = TheSubFruits.Where(x.FruitID == TheTable.FruitID && other conditions).Count(),
Count3 = TheSubFruits.Where(x.FruitID == TheTable.FruitID && other conditions).Count()
}).First()
问题是计数错误,如果我使用 .Single() 而不是 .First() 我还会收到“序列包含多个元素”错误。
为什么这个子查询返回的计数不与 3 个子查询相同?我需要改变什么?
【问题讨论】:
-
TheTable.FruitID 等于 x.FruitID 其中 x.Field2 == 1 || x.Field2 == 2 || x.Field2 == 3
-
我想他还是想单独数水果。
-
您可以按 FruitID 分组,然后计算每个分组的数量。
-
@jdweng:实际的谓词比较复杂,按一个条件分组的方法是行不通的。
标签: c# linq linq-to-sql