Search code examples
c#linqcsvhelper

LINQ group by and writerecords


I have a csv file that contains cartoon characters with their classification. I want to group them by classification and count them based on the classification. I solved it by following an answer on Stack Overflow, but they just wrote the result to the console. I'd like to write it to a csv file with csvhelper, but I don't know how. For example: input:

id | classfication
1       Wolf 
2       Fish
3       Wolf

output:

classfication | count
    Wolf          2
    Fish          1

The code (it works fine, I just can't write it to a CSV file):

            foreach (var line in list.GroupBy(info => info.classfication)
                        .Select(group => new {
                            Metric = group.Key,
                            Count = group.Count()
                        })
                        .OrderBy(x => x.Metric))
            {
                var one = line.Metric;
                var two = line.Count;
                full = one + two;
            
            
            using (var writer = new StreamWriter("Projects\\Example\\Output.csv"))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csv.WriteRecords(full.ToList()); //I don't know what to write here, instead of 'full'
            }
            }

Solution

  • CsvWriter accepts a list of items, which will be written as CSV. So you don't need to loop over the list (with foreach). Instead, first create the groupedList, and then write that list to the file:

    // step 1, create the grouping
    var groupedList = list.GroupBy(info => info.classification)
                      .Select(grp => new 
                       {
                          Metric = grp.Key,
                          Count = grp.Count()
                       }) 
                       .ToList();
    
    // step 2, write to file
    using (var writer = new StreamWriter("Projects\\Example\\Output.csv"))
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    {
        csv.WriteRecords(groupedList); 
    }