用linq-读取Excel工作表,跳过重复的ID
在下面的excel文件中,我需要读取作为Student
类的行,这些类定义唯一ID的单个对象,然后获取与此学生关联的所有考试。
如果我使用下面的代码,我生成的学生数量等于行数,并且没有为每个对象学生指定考试列表。
IQueryable<Student> Students_var; var excel = new ExcelQueryFactory(fileName_global1); excel.AddMapping<Student>(x => x.ID, "STU_NO"); Students_var = from c in excel.Worksheet<Student>("Stu_Schedule") select c; List<Student> StudentList_c = Students_var.ToList();
我已经简化了你的问题,以便有一个工作单位的testing。
我在本地创build值,而不是从Excel文件中读取。
在我创build的值我有3项,但只有2名学生,所以我在validationLINQ查询返回总是2logging。
你可以在下面的代码中看到如何分组你的项目。
[Test] public void LinqSelect_MultipleRowsWithTheSameId_RemoveDuplicatedRecords() { var excel = new [] {new Student() {ID = 1,Exam = 1}, new Student() { ID = 1, Exam = 2 }, new Student() { ID = 2, Exam = 1 } }; IEnumerable<IGrouping<int,Student>> Students_var = from c in excel group c by c.ID into newExcel select newExcel; Assert.AreEqual(2, Students_var.ToList().Count); } public class Student { public int ID { get; set; } public int Exam { get; set; } }
您可以按学生ID进行分组,然后将每个考试添加到学生对象。
var grouped = StudentList_c.GroupBy(x => x.ID).Select(x => new Student { ID = x.Key, Exam = x.SelectMany(z=> z.Exam).ToList() }).ToList(); public class Student { public int ID { get; set; } public List<int> Exam { get; set; } }
var rows = excel.Worksheet<Student>("Stu_Schedule").ToList(); var groupedStudents = rows.GroupBy(y=>y.Id) .Select(x => new Student { ID = x.Key, Exam = x.SelectMany(z=> z.Exam).ToList() }).ToList();