Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I initialize an object in one statement using lambda for each syntax?

Tags:

c#

lambda

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 ?

like image 445
NooooobDeveloper Avatar asked Apr 28 '26 09:04

NooooobDeveloper


1 Answers

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.

like image 183
James Thorpe Avatar answered Apr 30 '26 23:04

James Thorpe