List <complextype>:需要对ComplexType </complextype>的属性执行linq查询

时间:2014-12-18 23:59:41

标签: c# linq math

作为一个例子,我有一个这样的类型:

public class Stuff
{
    public Double StuffAmount;
    public String StuffDescription;
    public DateTime StuffDate;
}

我需要检查标准偏差和I've found those solutions elsewhere on stackoverflow之类的内容。但要按照他们提出的方式来做,我需要做这样的事情:

List<Double> stuffAmounts = new List<Double>();

foreach (var s in List<Stuff>)
{ 
    stuffAmounts.Add(s.StuffAmount); 
}

//now I have a list of doubles that I can do frequently referenced math functions with

有没有做something like this而不必创建一个新列表,只使用已经有双打属性的复杂类型?

2 个答案:

答案 0 :(得分:2)

您可以执行以下某些操作

解决方案1 ​​

如上所述,您只需Select进入相应类型并将其传递给StandardDeviation方法

给出

public static double StandardDeviation(List<double> valueList)
{
    double M = 0.0;
    double S = 0.0;
    int k = 1;
    foreach (double value in valueList) 
    {
        double tmpM = M;
        M += (value - tmpM) / k;
        S += (value - tmpM) * (value - M);
        k++;
    }
    return Math.Sqrt(S / (k-2));
}

用法

List<Double> stuffAmounts = myListOfStuff.Select(s => s.StuffAmount).ToList()
double result = StandardDeviation(stuffAmounts);

解决方案2

或者您可以创建一个扩展方法并将标准数学计算放在一个地方

鉴于

public static class MathExtensions
{
   public static double StandardDeviation<T>(this List<T> list, Func<T, Double> selector) where T : class
   {
      var m = 0.0;
      var s = 0.0;
      var k = 1;
      foreach (var value in list.Select(selector))
      {
         var tmpM = m;
         m += (value - tmpM) / k;
         s += (value - tmpM) * (value - m);
         k++;
      }
      return Math.Sqrt(s / (k - 2));
   }
}

用法

var stuffs = new List<Stuff>();
var result = stuffs.StandardDeviation(x => x.StuffAmount);

答案 1 :(得分:1)

根据您的问题,我不是100%确定这是您想要的,但在我看来,您想要的只是不创建第二个列表并且为此您只需要将原始列表作为参数传递并访问您想要的适当的属性。像下面的东西

鉴于

public static double StandardDeviation(List<Stuff> valueList)
    {
        double M = 0.0;
        double S = 0.0;
        int k = 1;
        foreach (var value in valueList)
        {
            double tmpM = M;
            M += (value.StuffAmount - tmpM) / k;
            S += (value.StuffAmount - tmpM) * (value.StuffAmount - M);
            k++;
        }
        return Math.Sqrt(S / (k - 2));
    }

用法

double stdDev = StandardDeviation(data)