AddMapping列列表

时间:2016-09-19 07:36:38

标签: c# excel linq grouping

我有以下Student课程,每个ID都有一个考试列表,我需要将考试列映射到Exams_Line_list的属性。以下代码返回空Exams_Line_list

public class Student
    {
        string id;
        public List<String> exams_Line_list = new List<String>();
        public String exams_Line1;

        public string Exams_Line1
        {
            get { return exams_Line1; }
            set { exams_Line1 = value; }
        }

        public string ID
        {
            get { return id; }
            set { id = value; }
        }

        public List<String> Exams_Line_list
        {
            get { return exams_Line_list; }
            set { exams_Line_list = value; }
        }
}

阅读Excel表格:

IQueryable<Student> Students_var;
var  excel = new ExcelQueryFactory(fileName_global1);

excel.AddMapping<Student>(x => x.ID, "STU_NO");
excel.AddMapping<Student>(x => x.Exams_Line1, "Exam");
Students_var = from c in excel.Worksheet<Student>("Stu_Schedule")
               select c;

List<Student> StudentList_c = Students_var.ToList();

var grouped = StudentList_c.GroupBy(x => x.ID).Select(x => new Student
              {
                ID = x.Key,
                Exams_Line_list = x.SelectMany(z => z.Exams_Line_list).ToList()
              }).ToList();

foreach (var r in grouped)
{
    Console.WriteLine(r.ID);
        foreach (String s1 in r.Exams_Line_list)
                    Console.WriteLine(s1);
}

架构:

enter image description here

我添加了一个String属性来映射Exam列,(Exams_Line1) 断点StudentList_c enter image description here

现在它会读取所有行,包括每个考试值的重复ID,但是如何将它们分组到定义的列表(Exams_Line1

1 个答案:

答案 0 :(得分:0)

可能你可以使用这个:

var grouped = StudentList_c.GroupBy(x => x.ID).Select(x => new Student
{
   ID = x.Key,
   Exams_Line_list = x.Select(z => z.Exams_Line1).ToList()
}).ToList();

这里我假设Student_List包含与excel表中行相对应的所有行,Exams_Line1属性正在映射到Exam列。