TechCognition

Microsoft Visual Studio 2017 Promo Code

Change or Replace Some Properties Values of a C# List using Linq Lambda

Sometimes we will have requirement to change or replace specific property values and return all properties for a C# List. We can achieve this by using Linq Lambda expression.

Create simple Console application by using Microsoft Visual Studio 2017 and add Employee class.

public class Employee

{

        public int EmpId { get; set; } 

        public string EmpName { get; set; }

}

Let’s create some Employee objects and add these to Employee list.

          List<Employee>listEmployees = new List<Employee>(); 

            Employee obj1 = new Employee();

            obj1.EmpId = 100;

            obj1.EmpName = "Raj";

            listEmployees.Add(obj1); 

            Employee obj2 = new Employee();

            obj2.EmpId = 101;

            obj2.EmpName = "John";

            listEmployees.Add(obj2); 

            Employee obj3 = new Employee();

            obj3.EmpId = 102;

            obj3.EmpName = "David";

            listEmployees.Add(obj3); 

As shown we have created the three Employee objects and added to the listEmployees list. Now I want to replace employee name “Raj” with “Admin” and want to return all properties. Use Linq and apply lambda expression as shown below to achieve this.

listEmployees = listEmployees.Select(c => { c.EmpName = c.EmpName.Replace("Raj", "Admin"); return c; }).ToList<Employee>();

Above code returns a list of Employees by replacing employee name “Raj” with “Admin” and returns all properties including EmpId.


 

Add comment

Loading

© Copyright 2017 www.techcognition.com | Sitemap