【问题标题】:LINQ get the average of columns and write to csvLINQ 获取列的平均值并写入 csv
【发布时间】:2020-10-14 16:57:59
【问题描述】:

我试图通过他们的分类来选择卡通人物,然后平均他们的攻击和防御属性。然后最后将其写入 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);
            }

【问题讨论】:

    标签: c# linq csvhelper


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢您的快速回答,完美运行。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多