3

I have a list of employees, and all of them have another list nested which is called the DisplayList.

Now not all the employees have the same amount of DisplayFields. So I wish to get those with the highest DisplayFields, so that I can incorporate everyone in the display.

At the moment I have the following :-

            int iMaxDisplayCount = 0;
        foreach (Employee employee in employeeList)
        {
            int iDisplayCount = employee.EmployeeDisplayCollection.Count;
            if (iDisplayCount > iMaxDisplayCount)
                iMaxDisplayCount = iDisplayCount;
        }

        var employees = employeeList.GroupBy(p => p.EmployeeDisplayCollection.Count == iMaxDisplayCount).Select(g => g.ToList());  
        foreach(var employeeHighList in employees)
        {
            foreach (var employee in employeeHighList) 
            {         

            }         
        } 

however for some reason, I am getting all the employees in the employeeHighList and not just the ones who have the highest display count.

I think the GroupBy is not correct, but don't know what's wrong with it.

Any help will be very much appreciated!

Thanks

JMon
  • 3,387
  • 16
  • 63
  • 102
  • 1
    Your question isn't really clear. What do you mean by "so that I can incorporate everyone in the display"? Please read http://tinyurl.com/so-hints and edit your question to be clearer. – Jon Skeet Apr 25 '12 at 09:32

1 Answers1

14
var max = employeeList.Max(e=>e.EmployeeDisplayCollection.Count);

var maxEmp = employeeList.Where(e=>e.EmployeeDisplayCollection.Count == max)
                         .ToList()
Adrian Iftode
  • 15,465
  • 4
  • 48
  • 73
  • @AdamHouldsworth, yes, I hope EmployeeDisplayCollection is always an instance – Adrian Iftode Apr 25 '12 at 09:50
  • Hi Adrian EmployeeDisplayCollection is a list of display vars pertaining to each employee. So it is an instace for every employee yes. And thanks again for this LINQ! I really like the solution – JMon Apr 25 '12 at 12:18
  • this code loops through the outer list two times! You can do it with only one loop! Store the index of the list with max count as you loop through the outer list so you don't have to go back and see which list had the max count! – Shane Aug 17 '18 at 18:38