我如何在C#中实现这一目标

时间:2012-02-27 15:59:10

标签: linq-to-sql

如何在C#中有条件地聚合

与以下vb代码类似:

Dim movement = From item In dbo.VIEWITEMMOVEMENTs
               Where item.DATETRANSFERRED.Value.Date = Me.DateTimePicker1.Value.Date
               Group By item.DATETRANSFERRED.Value.Date, item.ITEMDESCRIPTION
               Into moved = Group, sold = Sum(item.QUANTITYSOLD), [IN] = Sum(If(item.QUANTITY < 0.0, 0.0, item.QUANTITY)), Out = Sum(If(item.QUANTITY > 0, 0, item.QUANTITY))
               Select ITEMDESCRIPTION, sold, [IN], Out Order By ITEMDESCRIPTION Ascending
Me.DataGridView1.DataSource = movement

2 个答案:

答案 0 :(得分:0)

如果您尝试转换该代码段。你可以使用像

这样的转换器

VB to C#

希望这有帮助。

答案 1 :(得分:0)

 var result = (
                from item in dbo.VIEWITEMMOVEMENTs
                where item.DATETRANSFERRED.Value.Date == this.DateTimePicker1.Value.Date
                group item by new { item.DATETRANSFERRED.Value.Date, item.ITEMDESCRIPTION }
                into g
                select new
                {
                    g.Key.ITEMDESCRIPTION,
                    sold = g.Sum(x => x.QUANTITYSOLD),
                    IN = g.Sum(x => (x.QUANTITY <0 ? 0 : x.QUANTITY)),
                    Out = g.Sum(x => (x.QUANTITY > 0 ? 0 : x.QUANTITY))
                }
               ).OrderBy(d => d.ITEMDESCRIPTION);