【问题标题】:Return Standard Deviation of column values with other column value condition LINQ使用其他列值条件 LINQ 返回列值的标准偏差
【发布时间】:2019-05-14 22:21:01
【问题描述】:

我有一个表db.Men,它有三列

  • nvarchar "名称"
  • int "年龄"
  • nvarchar“状态”

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

我需要计算“Happy”或“Normal”年龄的平均值和标准差:

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();

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

【问题讨论】:

  • 在你的情况下标准差的公式是stdDev = Math.Sqrt((sum) / (ctx.Count()-1));(我认为...:P)

标签: c# linq conditional-statements standard-deviation


【解决方案1】:

Happy 年龄(或每个Status 一个)粘贴到一个列表中,然后计算标准差。本文作为确定标准偏差的良好过程:

Standard deviation of generic list?

类似:

var happyAges = ctx.Men.Where(i=>i.status == "Happy")Select(i=>i.age);
var happySd = CalculateStdDev(happyAges);

此外,您可以将标准偏差方法设为静态,并使用扩展方法在一个请求中完成所有操作。

【讨论】:

    【解决方案2】:

    我这样做了,它对我有用:

    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);
    

    【讨论】:

      猜你喜欢
      • 2015-03-29
      • 2018-03-08
      • 1970-01-01
      • 2021-03-06
      • 2015-03-05
      • 2022-07-20
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      相关资源
      最近更新 更多