If I have these two classes:
public class StudyClass
{
public string className { get; set; }
public List<Student> students { get; set; }
}
public class Student
{
public string studentName { get; set; }
}
Then I can initialize the StudyClass object like that:
var classObject = GetClassData(); // returns a big object with many properties that I don't need
var studyClass= new StudyClass() {
className = classObject.className
}
foreach(var student in classObject.students)
{
studyClass.students.add(new Student() {
studentName = student.Name
});
}
Is it possible to do it in a more simple way, by doing something like:
var classObject = GetClassData(); // returns a big object with many properties that I don't need
var studyClass= new StudyClass() {
className = classObject.className,
students = classObject.students.ForEach...// i am stuck here
}
If it's possible, is there any performance benefit or drawback by doing that ?
Yes, you can do this using the LINQ Select method followed by returning the results as a list using ToList:
var classObject = GetClassData();
var studyClass = new StudyClass {
className = classObject.className
students = classObject.students.Select(s => new Student { studentName = s.Name}).ToList()
};
This will enumerate classObject.students calling the lambda function once for each one, where the expression returns a new Student using the current value (s) to set the studentName property.
is there any performance benefit or drawback by doing that ?
It's unlikely to be any more performant; internally it still has to enumerate classObject.students and has to call the lambda method, while the original method has to make use of List.Add. You need to properly measure the timings to find out if it makes a worthwhile difference in your environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With