[英]read Excel sheet with linq- skip duplicated id
In following excel file, I need to read rows as Student
class which define single object for the unique ID and then get all exams associated with this student. 在下面的excel文件中,我需要读取作为
Student
类的行,它们为唯一ID定义单个对象,然后获得与该学生相关的所有考试。
If I used the following code I generate number of students equal to number of rows and without specifying exams list for each object student. 如果我使用以下代码,我生成的学生数量等于行数,而不指定每个对象学生的考试列表。
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();
I've simplified a your questions in order to have a working unit test. 我已经简化了你的问题,以便进行工作单元测试。
I'm creating the values locally instead of reading it from an excel file. 我在本地创建值而不是从excel文件中读取它。
in the values that I'm creating I have 3 items but only 2 students so I'm verifying that the linq query returns always 2 records. 在我正在创建的值中,我有3个项目,但只有2个学生,所以我验证linq查询总是返回2条记录。
you can see in the below code how to group your items. 您可以在下面的代码中看到如何对项目进行分组。
[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; }
}
You can group by the Student ID then add each exam to the Student Object. 您可以按学生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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.