LINQ具有多列和操作

时间:2013-09-19 13:53:36

标签: c# .net linq tsql entities

我正在尝试在LINQ上执行此操作:

select p.ProductID, p.ArticleCode, SUM((case h.OperationType when 0 then 1 else -1 end) * h.[Count])
from Products p
inner join StockItems s on p.ArticleCode = s.ArticleCode
inner join StockHistorical h on s.ArticleID = h.ArticleID
where h.[Date] < '23/08/2013 11:30:00'
group by p.ProductID, p.ArticleCode

我有这个:

        var products = (from p in e.Products
                        join s in e.StockItems on p.ArticleCode equals s.ArticleCode
                        join h in e.StockHistoricals on s.ArticleID equals h.ArticleID
                        where h.Date < DateTime.Parse("23/08/2013 11:30:00")
                        group p by p.ProductID into StockResult
                        select new {  });

任何人都知道我该怎么做

SUM((case h.OperationType when 0 then 1 else -1 end) * h.[Count])

使用LINQ?

谢谢!

我忘了说问题是“分组依据”,因为我无法访问StockResult组中的OperationType属性。

解决!关键是:

let combined = new 
{
    Product = p,
    HistoryCount = (h.OperationType == 0 ? 1 : -1) * h.Count
}

3 个答案:

答案 0 :(得分:2)

...
let combined = new 
{
    Product = p,
    HistoryCount = (h.OperationType == 0 ? 1 : -1) * h.Count
}
group combined by combined.Product.ProductID into StockResult
select new
{
    ProductID = StockResult.Key,
    Total = StockResult.Sum(x => x.HistoryCount)
}

答案 1 :(得分:0)

这不是直接翻译,但我会选择:

(h.Count(his => his.OperationType != 0) 
    - h.Count(his => his.OperationType == 0))
    * h.Count()

它应该在功能上等同,似乎更能代表你想要做的事情。

答案 2 :(得分:0)

你试图做这样的事吗? 我不确定这会起作用。

select new
{
S=Sum(((h.OperationType)!=0?-1:1)*h.Count)
}