简体   繁体   English

使用Linq计算C#中的平均评分

[英]Using Linq to calculate rating average in C#

I have an array ratings where ratings[i] = j means there are j ratings of i, where i is between 1 and 10. How can I use linq to calculate the average rating ? 我有一个数组等级,其中等级[i] = j表示i的j个等级,其中i在1到10之间。如何使用linq计算平均等级?

for (int i = 1; i <= 10;i++)
            {
                sum += i * ratings[i];
                nr += ratings[i];
            }
ratingAvg = sum / nr;

If i use ratings.Sum() / ratings.Count() it doesn't do what I want. 如果我使用ratings.Sum() / ratings.Count()它并不能满足我的要求。 I would need to do something like ratings.Sum(w => index_of_w_in_the_array * w.value). 我需要做一些类似ratings.Sum(w => index_of_w_in_the_array * w.value).

There are several ways to do this, for example using Select to involve the index of each rating in the calculation: 有多种方法可以执行此操作,例如,使用“ Select在计算中包含每个等级的索引:

var average = ratings.Select((r, n) => r * n).Sum() / ratings.Sum();

If the ratings themselves are integers you 'll need to cast one side of the above to double so that you don't get integer division on the result. 如果等级本身是整数,则需要将上述内容的一侧进行double以使结果不被整数除。

Just keep a running sum and a running count of items. 只需保持一个连续的总和和项目的连续计数。 For each item in the list add to the total count, and add to the running sum based on the count of that value multiplied by the value itself: 对于列表中的每个项目,将其添加到总计数,然后根据该值的计数乘以值本身,将其添加到运行总和:

int sum = 0;
int count = 0;
for(int i = 0; i < array.Length; i++)
{
    sum += array[i] * i;
    count += array[i];
}
double average = sum / (double)count;

Here is a LINQ solution, that looks nice, but is going to be quite a bit less efficient: 这是一个LINQ解决方案,看起来不错,但效率会大大降低:

var average = array.SelectMany((n, i) => Enumerable.Repeat(n, i))
    .Average();

ratings.Sum() / ratings.Count() should work. ratings.Sum() / ratings.Count()应该可以。 If it doesn't, you need to be a lot more detailed than "doesn't do what I want." 如果没有,您需要比“不做我想做的事情”更为详细。

And, if all else fails, try: 并且,如果其他所有方法均失败,请尝试:

ratings.Average();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM