user1583754
user1583754

Reputation: 59

Group and sum and fetch with condition in Linq

Have a object collection like below

UtilityName ="tank1";
Period ="A";
Value=170

UtilityName ="tank1";
Period ="B";
Value=120


UtilityName ="tank2";
Period ="A";
Value=220


UtilityName ="tank2";
Period ="B";
Value=260

UtilityName ="tank3";
Period ="A";
Value=0

UtilityName ="tank3";
Period ="B";
Value=0

UtilityName ="tank4";
Period ="A";
Value=10

UtilityName ="tank4";
Period ="B";
Value=0

Need a Linq query where i can group objects by UtilityName and sum by "Value" property and get only those objects whose summation is greater then Zero. In the above example, i need collection which includes all object except/ excluding Tank 3 object whose summation of Value is 0;

Upvotes: 0

Views: 93

Answers (4)

Wasif Hossain
Wasif Hossain

Reputation: 3940

You can try this:

var qry = from obj in list
          group obj by obj.UtilityName into g
          where g.Sum(x => x.Value) > 0
          select new { UtilityName = g.Key, Value = g.Sum(x => x.Value)};

Upvotes: 1

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

You can just remove the values with a zero first (if all elements with same UtilityName has a 0 value, they won't be present in the groups).

If you don't have negative values, this will be the easiest way.

But if you need a count, for example, this won't work anymore.

var result = list.Where(m => m.Value > 0)
                 .GroupBy(m => m.UtilityName)
                 .Select(m => new {
                   UtilityName = m.Key,
                   SumValues = m.Sum(x => x.Value)
                 });

Less "fragile" :

   var result = list
                   .GroupBy(m => m.UtilityName)
                   .Select(m => new {
                      UtilityName = m.Key,
                      SumValue = m.Sum(x => x.Value)
                   })
                   .Where(m => m.SumValue > 0);

EDIT

Not clear if you want, as result, a new object with the sum, or if the sum is just a way to exclude some objects...

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

list.GroupBy(x => x.UtilityName)
    .Where(x => x.Sum(y => y.Value) > 0)
    .SelectMany(g => g);

Upvotes: 0

Jim Bolla
Jim Bolla

Reputation: 8295

Something like this:

var result = objects
    .GroupBy(
        o => o.UtilityName,
        o => o,
        (name, grouping) => new
                            {
                                Sum = grouping.Sum(o => o.Value),
                                Items = grouping
                            })
    .Where(a => a.Sum > 0)
    .SelectMany(a => a.Items);

Upvotes: 0

Related Questions