Maro Maro - 2 months ago 13
C# Question

Group By records from csv file

I'm loading CSV file

enter image description here

Into:

public class ReleaseVersion
{
public string Version { get; set; }
public DateTime? ReleaseDate { get; set; }
public IEnumerable<ReleaseNote> ReleaseNotes { get; set; }

}

public class ReleaseNote
{
public string Description { get; set; }
public string Progress { get; set; }
public string Status { get; set; }
}


How can i group all records by version and return list of ReleaseVersion?

Here is what i did, however i did't know how to group by first column which is the version column in the file.

var records = csvLinesData.Select(data => new ReleaseVersion
{

Version = data[0],
ReleaseDate = TryParse(data[1]),
// add list of ReleaseNote ??
}).ToList();

Answer

Just GroupBy on the first item:

  DateTime date;

  var records = csvLinesData
    .GroupBy(line => line[0]) // line[0] is version we want to group by on
    .Select(chunk => new ReleaseVersion() {
       Version = chunk.Key,
       ReleaseDate = DateTime.TryParse(chunk.First()[1], out date) 
          ? (DateTime?) date 
          : null,
       ReleaseNotes = chunk
         .Select(item => new ReleaseNote() {
            Description = item[2],
            Progress = item[3],
            Status = item[4], }) 
         .ToArray(), })
    .ToList();