I have a class with these properties:
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
public GradeLevel Year;
public List<int> ExamScores;
And a method:
protected static List<Student> students = new List<Student>
{
new Student {FirstName = "Terry", LastName = "Adams", ID = 120,
Year = GradeLevel.SecondYear,
ExamScores = new List<int>{ 99, 82, 81, 92}},
new Student {FirstName = "Fadi", LastName = "Fakhouri", ID = 116,
Year = GradeLevel.ThirdYear,
ExamScores = new List<int>{ 99, 81, 90, 94}},
new Student {FirstName = "Hanying", LastName = "Feng", ID = 117,
Year = GradeLevel.FirstYear,
ExamScores = new List<int>{ 90, 94, 81, 82}},
}
Next step:
public void GroupByMark()
{
students.ForEach(mark =>
{
var queryNumericRange =
from student in students
group new {student.FirstName, student.LastName} by mark
into percentGroup
orderby percentGroup.Key
select percentGroup;
foreach (var studentGroup in queryNumericRange)
{
Console.WriteLine("Key: {0}", (studentGroup.Key));
foreach (var item in studentGroup)
{
Console.WriteLine("\t{0}, {1}", item.LastName, item.FirstName);
}
}
});
}
Result:
key: test.StudentClass+Student
Adams, Terry
Fakhouri, Fadi
Feng, Hanying
key: test.StudentClass+Student
Adams, Terry
Fakhouri, Fadi
Feng, Hanying
key: test.StudentClass+Student
Adams, Terry
Fakhouri, Fadi
Feng, Hanying
Desired result:
key: 99
Adams, Terry
Fakhouri, Fadi
key: 82
Adams, Terry
Feng, Hanying
key: 81
Adams, Terry
Fakhouri, Fadi
key: 92
Adams, Terry
key: 90
Fakhouri, Fadi
Feng, Hanying
key: 94
Fakhouri, Fadi
Feng, Hanying
So, for each mark I would like to display list of students, who received that particular mark. Do you have any ideas how to do it?
It sounds like you want to create a sequence of student/mark pairs, and then group by the mark:
var studentsByMark = from student in students
from mark in student.ExamScores
group student by mark;
foreach (var group in studentsByMark)
{
Console.WriteLine("{0}:", group.Key); // Mark
foreach (var student in group)
{
Console.WriteLine("{0}, {1}", student.LastName, student.FirstName);
}
}
See more on this question at Stackoverflow