LINQ 获取列的平均值并写入 csv

LINQ get the average of columns and write to csv

我正在尝试select卡通人物的分类,然后平均他们的攻击和防御属性。然后最后将它写入一个csv文件。 输入:

classfication | attack | defense
   Wolf           5        6
   Wolf           2       12

输出:

attack_average | defense_average
     3.5               9

我写了一段代码,可以得到平均值,但不能对它们使用 'ToList()',也不能将它们写入一个 csv 文件,因为我有两个变量。

            var list = list.Where(x => x.classfication.Equals("Wolf"));
            var def = list.Select(x => x.defense).Average();
            var atk = list.Select(x => x.attack).Average();

            using (var writer = new StreamWriter("D:\Example\Example.csv"))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
               csv.WriteRecords(def);
            }

理论上,您可以根据已有的数据创建一个新的列表或数组。

csv.WriteRecords(new[]{new { attack_average = atk, defense_average = def }});

但考虑“分组”原始输入并获取每组平均值可能更有用。

        var averagesByClass = list
            .Where(x => x.classfication.Equals("Wolf")) // might not want this?
            .GroupBy(x => x.classfication)
            .Select(g => new 
                {
                    classification = g.Key, // Remove this if you don't want it
                    attack_average = g.Select(x => x.defense).Average(),
                    defense_average = g.Select(x => x.attack).Average(),
                })
            .ToList();

        using (var writer = new StreamWriter("D:\Example\Example.csv"))
        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
           csv.WriteRecords(averagesByClass);
        }