LINQ - Help me figure this out with an example that I think LINQ should solve!

I am trying to get into LINQ to objects, as I can see its power. Fortunately, I have a question that, in my opinion, LINQ should solve.

Here is the question (details are an example);

public class SchoolClass { public int ID; public string Name; public string Teacher; public string RoomName; public string Student_Name; public int Student_Age; } 

As you can see from the example, there is a one-to-many relationship between ClassName, Teacher and Room and students, i.e. there are potentially many students in one class.

If we have a list, can LINQ create a list but have only one instance identifier, name, teacher, room name, and ArrayList from Student_Name and Age?

By producing this:

 public class Students { public string Student_Name; public int Student_Age; } public class SchoolClass { public int ID; public string Name; public string Teacher; public string RoomName; public ArrayList Students; } 

Essentially using LINQ to clear the list to a more logical structure?

To give an example in this example. The second structure is used by the DataGrid to create a Teacher-Child relationship. We save SchoolClass and StudentInformation in classes as shown above. It would be nice to use LINQ to be able to convert our initial list into a structure that a DataGrid can use.

+4
source share
2 answers

I changed ArrayList to List<Students> and:

  List<SourceData> source = new List<SourceData>(); //...your data here ;-p var classes = (from row in source group row by new { row.ID, row.Name, row.Teacher, row.RoomName } into grp select new SchoolClass { ID = grp.Key.ID, Name = grp.Key.Name, Teacher = grp.Key.Teacher, RoomName = grp.Key.RoomName, Students = new List<Students>( from row in grp select new Students { Student_Age = row.Student_Age, Student_Name = row.Student_Name }) }).ToList(); 
+6
source

If I understand this correctly, I would think that the best way to implement the SchoolClass class is to create a Student class (perhaps a LINQ-to-SQL object if you use it) and have a common list of students like something like this:

 public class SchoolClass { public int ID; public string Name; public string Teacher; public string RoomName; public List<Student> Students; } 

Then the list of students can be filled using the linq query, although I'm not sure exactly how without additional information.

Hope this helps.

+1
source

All Articles