score:3

``````weightedAverage = group.Sum(r => r.Field("EXEC_QTY") * r.Field("price"))
/ group.Sum(r => r.Field("EXEC_QTY"));
``````

Add Convert.ToDouble if you really need it.

Since you comment that qty is a double and price is a decimal:

``````weightedAverage = group.Sum(r => (decimal)r.Field("EXEC_QTY") * r.Field("price"))
/ group.Sum(r => (decimal)r.Field("EXEC_QTY"));
``````

(Wouldn't it make more sense for price to be decimal and quantity to be a double? Or for both to be decimal?)

score:0

``````    class Data
{
public int Qty { get; set; }
public double Price { get; set; }
public string Date { get; set; }
}
static void Main(string[] args)
{
var data = new Data[] {
new Data { Qty = 5, Price = 2, Date = "1/25"  },
new Data { Qty = 6, Price = 1, Date = "1/25"  },
new Data { Qty = 8, Price = 3, Date = "4/25"  },
new Data { Qty = 1, Price = 2, Date = "4/25"  },
};

var weighted = data.GroupBy(x => x.Date)
.Select(group => new Data {
Date = group.Key,
Qty = group.Sum(i => i.Qty),
Price = group.Sum(i => i.Price * i.Qty) / group.Sum(i => i.Qty)
});
}
``````

score:0

I would do something like this:

``````var results = ToCalc.AsEnumerable()
.Select(grp =>
{
var quantity = grp.Sum(r => r.Field("EXEC_QTY"));
var avg = grp.Sum(r => r.Field("EXEC_QTY") * r.Field("price")) / quantity;
return new {
Quantity = quantity,
WeightedAverage = avg
};
});
``````

`results` would then be an enumerable of anonymous objects containing the information you want, it much more accessible structure.

score:0

You could perform all grouping inside one method by using this `Enumerable.GroupBy`overload:

``````var groups = ToCalc.AsEnumerable()
.GroupBy(r => r.date, (k, g) => new
{
date = k,
qty = g.Sum(i => i.qty),
price = g.Sum(i => i.qty * i.price) / g.Sum(i => i.qty)
});
``````

This will give you something like:

``````{ date = "1/25", qty = 11, price = 1.4545454545454546 }
{ date = "4/25", qty = 9, price = 2.8888888888888888 }
``````