使用其他列值条件 LINQ 返回列值的标准偏差

我有一张桌子,db.Men有三列

  • nvarchar "名称"

  • 诠释“年龄”

  • nvarchar“状态”

Status列只有三个值:“Happy”、“Normal”和“Bad”。

我需要计算“快乐”或“正常”年龄的平均值和标准差:

using System.Linq 


var ctx     = new DataClasses1DataContext();


double? avg = (from n in ctx.men

               where n.status == "Happy"

               select n.age).Average();


int? sum    = (from n in ctx.men

               where n.status == "Happy"

               select n.age).Sum();

我计算了平均值和总和。如何计算此条件状态下的标准差?


撒科打诨
浏览 84回答 2
2回答

至尊宝的传说

Happy将年龄(或每个年龄)粘贴Status到列表中,然后计算标准偏差。本文作为确定标准偏差的良好过程:所以像:var happyAges = ctx.Men.Where(i=>i.status == "Happy")Select(i=>i.age);var happySd = CalculateStdDev(happyAges);此外,您可以将标准偏差方法设为静态,并使用扩展方法在一个请求中完成所有操作。

鸿蒙传说

我这样做了,它对我有用:int?[] array = (from a in ctx.men where a.status == "Happy" select a.age).ToArray();double? AVG = array.Average();double? SumOfSquaresOfDifferences = array.Select(val => (val - AVG) * (val  - AVG)).Sum();double? SD = Math.Sqrt(Convert.ToDouble(SumOfSquaresOfDifferences) / array.Length);
打开App,查看更多内容
随时随地看视频慕课网APP