Home > Software engineering >  How to return filtered list from another list
How to return filtered list from another list

Time:12-05

On my application I'm creating another view for statistics. The table in database has ScheduleId, Line, OperatorId, Shift, Function. From all records in db I want to take all employees from one ScheduleId. I do filter them by 'Working Line' however I need total number of employees. Any help how to achieve this?

.cshtml

  @foreach (var schedule in @Model.AllSchedules.DistinctBy(x => x.ScheduleId))
        {
            <table>
                <thead>
                    <tr>
                        <td>Line</td>
                        <td>Emploees</td>
                        <td></td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>@schedule.Line</td>
                        <td>@schedule.OperatorId</td>
                    </tr>
                </tbody>
            </table>
        }

Image

CodePudding user response:

however I need total number of employees

outside of the loop, it will return only 1 number :

total number of employees:@Model.AllSchedules.DistinctBy(x => x.OperatorId).Count()

@Maria's solution inside the loop, foreach line total number of employees:

@Model.AllSchedules.Where(x => x.ScheduleId == schedule.ScheduleId).Count()

CodePudding user response:

If you do a .GroupBy() rather than .DistinctBy() in your foreach, you can simply check the .Count() of the group to count the number of employees with the given ScheduleId.

The Line and OperatorId then need to be read from the first element in the group.

@foreach (var scheduleGroup in @Model.AllSchedules.GroupBy(x => x.ScheduleId))
{
    <table>
        <thead>
            <tr>
                <td>Line</td>
                <td>Operator ID</td>
                <td>Employees</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>@scheduleGroup.First().Line</td>
                <td>@scheduleGroup.First().OperatorId</td>
                <td>@scheduleGroup.Count()</td>
            </tr>
        </tbody>
    </table>
}
  • Related