简体   繁体   English

使用 LINQ 计算 Lists int C# 字典的平均值

[英]Calculate the average of Lists int C# Dictionary using LINQ

I have a dictionary containing n pair key/value and I want to get the total average of the first two values in each list in my dictionary.我有一个包含 n 对键/值的字典,我想获得字典中每个列表中前两个值的总平均值。 Here is an example:这是一个例子:

    private Dictionary<int, List<float>> _myValues = new Dictionary<int, List<float>>
    {
        {1, new List<float>{0.1f, 0.2f, 0.3f},
        {2, new List<float>{0.4f, 0.5f, 0.6f, 0.7f},
        {3, new List<float>{0.8f}
    };

For this example, I want the average of these values ( 0.1f , 0.2f , 0.4f , 0.5f , 0.8f ).对于这个例子,我想要这些值的平均值( 0.1f0.2f0.4f0.5f0.8f )。

I see that I can do this using for/foreach loop, but I wonder if it's possible to get that average using a simple LINQ query.我看到我可以使用 for/foreach 循环来做到这一点,但我想知道是否可以使用简单的 LINQ 查询来获得该平均值。

For this example, I want the average of these values (0.1f, 0.2f, 0.4f, 0.5f, 0.8f).对于这个例子,我想要这些值的平均值(0.1f、0.2f、0.4f、0.5f、0.8f)。

Dictionary<int, List<float>> _myValues = new Dictionary<int, List<float>>
{
    {1, new List<float>{0.1f, 0.2f, 0.3f}},
    {2, new List<float>{0.4f, 0.5f, 0.6f, 0.7f}},
    {3, new List<float>{0.8f}}
};

var result = _myValues.Values.SelectMany(z => z.Take(2)).Average();

Values will get the values from the Dictionary (ie ignore the Keys since they don't impact the result). Values将从Dictionary中获取值(即忽略Keys ,因为它们不会影响结果)。 Take(2) will get the first two entries from each list. Take(2)将从每个列表中获取前两个条目。 SelectMany will effectively concatenate all of those two entries into a single projection. SelectMany将有效地将所有这两个条目连接到一个投影中。 And Average will average them.Average将对它们进行平均。

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

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