estoy tratando de escribir un linq que devolverá la identificación del empleado que tiene la mayor cantidad de entradas en la tabla.
Así es como se ve mi clase
public class TrainingEmployee { public int EmployeeId { get; set; } public int TrainingId { get; set; } public List<TrainingEmployee> GenerateData() { return new List<TrainingEmployee>() { new TrainingEmployee() { EmployeeId = 1, TrainingId = 2}, new TrainingEmployee() { EmployeeId = 1, TrainingId = 2}, new TrainingEmployee() { EmployeeId = 1, TrainingId = 2}, new TrainingEmployee() { EmployeeId = 1, TrainingId = 2}, new TrainingEmployee() { EmployeeId = 2, TrainingId = 3}, new TrainingEmployee() { EmployeeId = 2, TrainingId = 3}, new TrainingEmployee() { EmployeeId = 2, TrainingId = 3}, new TrainingEmployee() { EmployeeId = 2, TrainingId = 3}, new TrainingEmployee() { EmployeeId = 2, TrainingId = 5}, new TrainingEmployee() { EmployeeId = 2, TrainingId = 5}, new TrainingEmployee() { EmployeeId = 2, TrainingId = 1}, }; } }Y así es como se ve mi código hasta ahora
var lista = new TrainingEmployee(); var data = lista.GenerateData().GroupBy(x => x.EmployeeId); var maxValue = 0; var employeeId = 0; foreach (var group in data) { var currentlyGroupCount = group.Count(); if(currentlyGroupCount > maxValue) { maxValue = currentlyGroupCount; employeeId = group.Key; } } Console.WriteLine("Value: {0} employeeid: {1}", maxValue, employeeId);¿Cómo puedo hacer el código anterior en solo un linq sin usar tanto código?
Puedes ordenarlo de forma descendente y seleccionar el primero:
var employee = GenerateData() // group on EmployeeId .GroupBy(e => e.EmployeeId) // reverse order it on count .OrderByDescending(g => g.Count()) // select the first .FirstOrDefault(); // check if the query returned anything other than default. if(employee != default) Console.WriteLine("Value: {0} employeeid: {1}", employee.Count(), employee.EmployeeId);Otro enfoque similar a la respuesta de jeroen-van-langen pero usando MaxBy () de MoreLINQ:
GenerateData() .GroupBy(e => e.EmployeeId) .MaxBy(e => e.Count());Esto también devolvería varias identificaciones si varios empleados tuvieran el mismo "recuento máximo"; una posibilidad en su escenario.
Esto evalúa Count () una vez para cada grupo de empleados, por lo que tiene un poco más de rendimiento, también permite obtener tanto el ID de empleado como el recuento máximo.
var mostFrequentEmployeeId = GenerateData() .GroupBy(x => x.EmployeeId, (employeeId, employeesGroup) => new { employeeId, count = employeesGroup.Count() }) .OrderByDescending(x => x.count) .FirstOrDefault()? .employeeId;