Royi Namir
Royi Namir

Reputation: 148524

Summing datatable in 1 linq expression?

I have this datatable :

enter image description here

I also have a class which contains two properties which should hold the sum for each Column :

class MyClass
{
 public decimal CatSum {get;set;}
 public decimal DogSum {get;set;}
}

I currently fill those props via :

 myClass.CatSum = dt.AsEnumerable().Sum(r => r["Cat"].ToDecimalOrZero());
 myClass.DogSum = dt.AsEnumerable().Sum(r => r["Dog"].ToDecimalOrZero())

Is there a way to fill (or create new class with those props) those props with 1 linq query ? ( I dont have any groupby field here)

;

Upvotes: 3

Views: 100

Answers (3)

sloth
sloth

Reputation: 101042

Why use Linq at all?

var myClass = new MyClass
{
    CatSum = (decimal)dt.Compute("SUM(Cat)", ""),
    DogSum = (decimal)dt.Compute("SUM(Dog)", "")
}

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

You can use instance of MyClass as accumulator and aggregate results into it:

var myClass = dt.AsEnumerable()
                .Aggregate(new MyClass(),
                           (a,r) => {
                                a.CatSum += r["Cat"].ToDecimalOrZero();
                                a.DogSum += r["DogS"].ToDecimalOrZero();
                                return a;
                           });

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

A Sum is an aggregate query, you cannot use a single LINQ query to assign the 2 properties.

Upvotes: 2

Related Questions