Question

I am using C# (.NET 4.0). I have a

class Employee
{
    public string Location { get; set; }
    public int ID { get; set; }
    public string FilterType { get; set; }

    public Employee(string name, int id, string fType)
    {
        Location = name;
        ID = id;
        FilterType = fType;
    }
}


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

Employee e = new Employee("[IND].[MH].&1", 1, "="); empList.Add(e);
e = new Employee("[SNG].[Tampines].&1", 7, "="); empList.Add(e);
e = new Employee("[IND].[MP].&2", 5, "="); empList.Add(e);
e = new Employee("[USA].[NYC].&2", 9, "="); empList.Add(e);
e = new Employee("[IND].[MH].&3", 3, "="); empList.Add(e);
e = new Employee("[IND].[MP].&1", 4, "="); empList.Add(e); 
e = new Employee("[SNG].[Bedok].&1", 6, "="); empList.Add(e);
e = new Employee("[USA].[NYC].&1", 8, "="); empList.Add(e);
e = new Employee("[IND].[MH].&2", 2, "="); empList.Add(e);

What I want to do :

  1. Split the 'name' property in the empList by '.&'
  2. This will return an array of 2 items. I will add array[0]into a dictionary.
  3. This will create list of unique items (Lets call it unique list)
  4. Then for every item in the unique list, I will loop over every item in empList and I will combine the name like this

if the item in unique list is '[USA].[NYC]', after looping over the empList, the output should be {[USA].[NYC].&1, [USA].[NYC].&2}. If the item in unique list is '[SNG].[Tampines]' the putput should be '{[SNG].[Tampines].&1}'

I can achieve this by doing something like this

Run a loop over empList - Split the name by '.&' and add the result in dictionary to ensure only unique items are added

Then run a loop over unique list - inside this loop run another loop on empList and check if the current item in empList contains item of uniqueList and do the string manipulation.

I wonder if there is a smarter way to achieve this.

Thanks

Was it helpful?

Solution

Yes, there is an easier way. You can use the LINQ group by functionality:

    var grouped = from emp in empList
                  group emp by emp.Location.Split('&')[0] into g
                  select new {LocCode = g.Key, Emps = g};

    foreach (var group in grouped) {
        // group.LocCode contains, e.g., [USA].[NYC].,
        // group.Emps contains all employees at this location
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top