I have a Student class as follows :
public class Student
{
public string Name { get; set; }
public int? Age { get; set; }
public bool? IsMale { get; set; }
}
and have list of courses where Students are assigned as a Dictionary, where all courses are stored as:
Dictionary<string, List<Student>>
where Key (string) is the code of the course and the Value (List< student >) are the students enrolled to that spesific course with all properties having a value.
Now I want to simplify the data set with only the Name of the students. So I will still have a Dictionary<string, List<Student>>
where only the Name
property is set for each and every Student
object.
How can I write such a LINQ query to fetch the data as I need?
CodePudding user response:
Since the dictionary implements IEnumerable<KeyValuePair<string, List<Student>>>
, you can write
var newDict = oldDict
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Select(s => new Student { Name = s.Name }).ToList()
);
Note that we have a nested LINQ query based on the list of students. It selects all the students of the list and creates new students with only the name set into a new list.
So, for each KeyValuePair, we keep the Key (the course code), but create a new Value as simplified list of students.
Instead, you could also create a Dictionary<string, List<string>>
with
var newDict = oldDict
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Select(s => s.Name).ToList()
);