Search code examples
c#ilist

Iterating through object properties in IList without a loop


Consider the following situation:

public class Employee
{
    public string Name {get; set}
    public string Email {get; set}
}

public class EnployeeGroup
{
    //List of employees in marketting
    public IList<Employee> MarkettingEmployees{ get; }

    //List of employees in sales
    public IList<Employee> SalesEmployees{ get; }
}

private EnployeeGroup GroupA;

int MarkettingCount;
string MarkettingNames;

MarkettingCount = GroupA.MarkettingEmployees.Count; //assigns MarkettingCount=5, this will always be 5-10 employees
MarkettingNames = <**how can i join all the GroupA.MarkettingEmployees.Name into a comma separated string?** >

//I tried a loop:
foreach(Employee MktEmployee in GroupA.MarkettingEmployees)
{
    MarkettingNames += MktEmployee.Name + ", ";
}

The loop works, but i want to know:

  1. Is Looping the most efficient/elegant way of doing this? If not then what are the better alternatives? I tried string.join but couldnt get it working..
  2. I want to avoid Linq..

Solution

  • You need a little bit of LINQ whether you like it or not ;)

    MarkettingNames = string.Join(", ", GroupA.MarkettingEmployees.Select(e => e.Name));