Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group By, Sum in LINQ

Tags:

c#

linq

suppose I have the following table:

user type amount
2    a    10
2    b    20
2    c    40
3    a    15
3    b    20
3    c    45

I want to replace (c) amount with (c - (a+b)) grouping by the user and type, how could I do this? thanks

like image 974
moeezed Avatar asked Oct 09 '22 22:10

moeezed


People also ask

How do you sum two columns in Linq?

Items select new { Sum(p. Total), Sum(p. Done)};

What is aggregate in Linq C#?

In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values.

How do you write a count query in Linq?

Count() methodIEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count(); NOTE: The Count() LINQ method (an extension method to IEnumerable<T> ) is slightly different from the Count property on List<T> .


1 Answers

Here is a way:

UPDATE (now using Sum):

from item in table
group item by item.user into g
let a = (from i in g where i.type == "a" select i.amount).Sum()
let b = (from i in g where i.type == "b" select i.amount).Sum()
let c = (from i in g where i.type == "c" select i.amount).Sum()
select c - (a + b);
like image 84
Steven Avatar answered Oct 12 '22 07:10

Steven