達倫,
只是一個快速的SO LINQ(雙關打算!!)讓你去直到進一步的答案到達:
Standard deviation of generic list?
希望這有助於
[編輯] - 基於上面的SO鏈接,你可以修改這一點,嘗試(靜態類中):
public static double StdDev(this IEnumerable<double> values)
{
double ret = 0;
if (values.Count() > 0)
{
//Compute the Average
double avg = values.Average();
//Perform the Sum of (value-avg)_2_2
double sum = values.Sum(d => Math.Pow(d - avg, 2));
//Put it all together
ret = Math.Sqrt((sum)/(values.Count()-1));
}
return ret;
}
再加上一點點覆蓋(我已經處理了,但後來改變了看這個鏈接http://help.syncfusion.com/ug_84/User%20Interface/WPF/Grid/default.htm?turl=Documents%2Fcustomsummaries.htm):
public static double StdDev<T>(this IEnumerable<T> values, Func<T, double?> selector)
{
double ret = 0;
var count = values.Count();
if (count > 0)
{
// Compute the Average
double? avg = values.Average(selector);
// Perform the Sum of (value-avg)^2
double sum = values.Select(selector).Sum(d =>
{
if (d.HasValue)
{
return Math.Pow(d.Value - avg.Value, 2);
}
return 0.0;
});
// Put it all together
ret = Math.Sqrt((sum)/(count - 1));
}
return ret;
}
,然後簡單地套用這樣:
var results = from res in dt.AsEnumerable()
group res by res.Field<string>(key)
into grp
orderby Convert.ToInt32(grp.Key)
select new
{
date = grp.Key,
sum = grp.Average(r => Convert.ToDouble(r.Field<string>(average))),
stdDev = gp.Select(s => Convert.ToDouble(s.Field<string>(average))).StdDev(),
// alternative override - note no need to convert
stdDev2 = gp.StdDev(s => s.Field<string>(average))
};
沒有測試過,所以可能無法馬上,但理論上是存在的。
部分,http://stackoverflow.com/questions/2253874/linq-equivalent-for-standard-deviation – 2011-03-03 10:53:53