Pregunta

How can I replicate following in LINQ

SELECT KEY_COLUMN,
        CASE WHEN SUM(COLUMN2) < 0 THEN SUM(COLUMN2) ELSE 0 END AS NewColumn
FROM TABLE
GROUP BY KEY_COLUMN

till now I could come up with following

var result = from a in source
               group a by a.Key_Column
                   into g
                   select new
                   {
                       Key_Column = g.Key,
                       NewColumn = g.Where(item => item.Column2 < 0)
                                    .Sum(item => item.Column2)
};

above code is not really summing up the Column2 before deciding if it's a negative number or not.

¿Fue útil?

Solución

var query = from a in db.Table
            group a by a.Key_Column into g
            let sum = g.Sum(item => item.Column2)
            select new {
               Key_Column = g.Key,
               NewColumn = sum < 0 ? sum : 0
            };

Otros consejos

isn't this the same ?

var query = from r in db.Table
  group r by r.KEY_COLUMN into g
  select new {
    KEY_COLUMN = g.Key,
    NewColumn = g.Sum(x => x.COLUMN2) < 0 ? g.Sum(x => x.COLUMN2) : 0
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top