Alex Rivera | Logout

Simple way to update IEnumerable objects using LINQ

Asked 2010-10-14T06:05:46.247
13

Assume I have a business object like this,

class Employee
    {
        public string name;
        public int id;
        public string desgination;
        public int grade;
    }

    List<Employee> lstEmp = new List<Employee>()
        {
            new Employee() { name="A",desgination="SE",id=1},
            new Employee() { name="b",desgination="TL",id=2},
            new Employee() { name="c",desgination="PL",id=3},
            new Employee() { name="d",desgination="SE",id=4},
            new Employee() { name="e",desgination="SSE",id=5},
        };

And if I want to update the employee grade to 3 whose designation is "SE", then I have to write something like this

lstEmp=lstEmp.Select(x =>
            {
                x.grade = (x.desgination == "SE") ? 3 : x.grade;
                    return x;
            }).ToList();

But here when using select it will generate new employee object everytime, not updating the existing lstEmp, so I have to reassgin the updated list to lstEmp.

It seems to me it affects the performance when updating large updates frequently. Is there a workaround for this?

Edit
Report

1 Answer

-2
lstEmp = lstEmp.Select(X => new Employee
        {
            desgination =X.desgination ,
            grade =X.desgination=="SE"?3:X.grade ,
            id=X.id ,
            name =X.name 
        }).ToList();
answered 2010-10-14T06:16:33.233

Your Answer