【问题标题】:AddMapping column to list将映射列添加到列表
【发布时间】:2016-09-19 20:29:01
【问题描述】:

我有以下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);
}

架构:

我添加了一个字符串属性来映射考试列,(Exams_Line1) 断点StudentList_c

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

【问题讨论】:

  • 能否在var grouped = StudentList_c.GroupBy... 行之前添加一个断点来检查StudentList_c 中的内容?特别要确保它包含正确的考试字符串值。
  • 是的,问题已更新
  • 好的,请看修改后的版本
  • 请检查
  • Exam 列到 Exams_Line1 的映射在哪里定义?这是按惯例发生的事情吗?

标签: c# excel linq grouping


【解决方案1】:

也许你可以用这个:

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 列。

【讨论】:

  • 错误 1 ​​无法将类型 'System.Collections.Generic.List' 隐式转换为 'System.Collections.Generic.List'
  • Exams_Line1 是字符串,但 Exams_Line_list 是列表
  • 谢谢,这节省了我的时间:)
  • Select 应该负责从 String 生成 List
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多