randomdude
randomdude

Reputation: 267

LINQ get the average of columns and write to csv

I'm trying to select cartoon characters by their classification, then average their attack and defense properties. Then finally write it to a csv file. input:

classfication | attack | defense
   Wolf           5        6
   Wolf           2       12

output:

attack_average | defense_average
     3.5               9

I wrote a code that can get the averages but can't use 'ToList()' on them and can't write them into one csv file because I have two variables.

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

Upvotes: 1

Views: 142

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156469

In theory you could just create a new list or array based on the data you already have.

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

But it may be more useful to think in terms of "grouping" the original input, and getting averages per group.

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

Upvotes: 1

Related Questions