-1

我有一个Student班级,每个学生的记录都有一个列表Results。我需要将结果导出到CSV并且我正在使用CsvHelper

public class Student
{
   public string Id { get; set; }
   public string Name { get; set; }
   public Result[] Grades { get; set; }
}

public class Result
{
   public string Subject { get; set; }
   public decimal? Marks { get; set; }
}

我正在使用参考地图来映射结果列表,但是在导出到 CSV 时会抛出错误。

映射代码

public sealed class StudentResultExportMap : ClassMap<Student>
{
    public StudentResultExportMap ()
    {
        AutoMap();
        References<GradesMap>(m => m.Grades);
    }
}

public sealed class GradesMap: ClassMap<Result>
{
    public GradesMap()
    {
        Map(m => m.Subject);
        Map(m => m.Marks);
    }
}

错误

没有为类型“{namespace}.GetStudentResults+Result[]”定义属性“System.String Subject”参数名称:属性

4

1 回答 1

1

不幸的是References<GradesMap>(m => m.Grades);,不适用于 Result 数组。它适用于个人结果。我有一个解决方案,它覆盖了压平成绩的ToString()方法。Result它可能对您有用,具体取决于您的需要。

public class Result
{
    public string Subject { get; set; }
    public decimal? Marks { get; set; }
    public override string ToString()
    {
        return $"{Subject} = {Marks}";
    }
}

对您的 StudentResultExportMap 稍作更改。您可以设置第二个数字.Index(2, 7)来处理您认为学生可能拥有的最大成绩数。

public sealed class StudentResultExportMap : ClassMap<Student>
{
    public StudentResultExportMap()
    {
        AutoMap();
        Map(m => m.Grades).Name("Grade").Index(2, 7);
    }
}

然后,您将获得每个等级Id, Name, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6toString()值。Result

var records = new List<Student>
{
    new Student{ Id = "1", Name = "First", Grades =  new [] {
        new Result { Subject = "Subject1", Marks = (decimal)2.5 } ,
        new Result { Subject = "Subject2", Marks = (decimal)3.5 } }},
    new Student{ Id = "2", Name = "Second", Grades =  new [] {
        new Result { Subject = "Subject1", Marks = (decimal)3.5 } ,
        new Result { Subject = "Subject2", Marks = (decimal)4.0 } }}
};

using (var writer = new StreamWriter("path\\to\\StudentResults.csv"))
using (var csv = new CsvWriter(writer))
{
    csv.Configuration.RegisterClassMap<StudentResultExportMap>();
    csv.WriteRecords(records);
}
于 2019-03-22T14:40:54.353 回答