How to generate comma-seperated employee name field from Employee List

Posted by Hmanjarawala under C# category on | Points: 40 | Views : 1716
This code snippet is for "How to generate comma-seperated employee name field from Employee List".

before doing that let's define Employee class

class Employee
public Id { get; set; }
public Name { get; set; }
public Age { get; set; }

now let's create List of Employee

var list = new List<Employee>() {
new Employee { Id=1, Name="Tarun", Age=31 },
new Employee { Id=2, Name="Rahul", Age=28 },
new Employee { Id=3, Name="Varsha", Age=28 },
new Employee { Id=4, Name="Keyuri", Age=23 },
new Employee { Id=5, Name="Keyur", Age=24 },
new Employee { Id=6, Name="Hims", Age=30 },
new Employee { Id=7, Name="Hetal", Age=26 },
new Employee { Id=8, Name="Amit", Age=25 },
new Employee { Id=9, Name="Hardik", Age=24 },

so, here we've list of 9 employees.
Now our goal is to fetch certain employees based on some criteria i.e. (Age>25), which ofcourse in form of list,
and then generate comma-seperated employee name string from this list.

To do that we didn't required iterate any loop. we can do this by firing just two statement.

string[] names = Array.ConvertAll<Employee, string>(list.Where(x=>x.Age>25), (Employee e) e.Name);
string commaSeperatedName = string.Join(",", names);

so, by this way we can get comma seperated name string.

Comments or Responses

Login to post response