Markku Rintala
Markku Rintala

Reputation: 149

How to use linq to calculate average from grouped data where value > 0 using let

I need to calculate an average of pretty complicated structure of enuberable data.

I have var table1Sum that is joined from two datatables. Another var table2Sum is also joined from two datatables. These two tables are joined into third table.

I need to get average of field3 grouped by field1 and field2 but the average calculation should not take into count when field3 == 0.0.

I tried

var table3 = from d in table1sum.Concat(table2sum)
             group d by new { d.field1, d.field2 } into dg
             let field3Average = dg.Where(g => g.field3 > 0.0).Average()
             select new
             {
             .....
             };

but this is not correct syntax for calculating average. I'm using let because I need calculated average later on in the select new part of my linq query.

(The normal average of all values goes well with let averageWithZeros = dg.Average(g => g.field3).)

Could somebody help me with correct syntax?

Upvotes: 1

Views: 375

Answers (1)

Nkosi
Nkosi

Reputation: 247183

you need to average field 3 after the filter

 let field3Average = dg.Where(g => g.field3 > 0.0).Average(g => g.field3)

Upvotes: 2

Related Questions