Home > database >  How Do I count the number of occurrences in the IEnumerable
How Do I count the number of occurrences in the IEnumerable

Time:03-09

I have this IEnumerable method in my razor page.

        @if (Orders.Any())
        {
            <table >
                <thead>
                   
                    <th>Driver Name</th>
                    <th>Delivery Orders</th>
                </thead>
                <tbody>
                    @foreach(var objOrders in Orders)
                    {
                    <tr>
                        <th>
                            @objOrders.Driver.UserName
                        </th>
                        <th>
                            @objOrders.Driver.FullName.Count()
                        </th>
                        <td>
                        </td>
                    </tr>
                    }
                </tbody>
            </table>
        }

Which is from here

private IEnumerable<OrderDTO> Orders { get; set; } = new List<OrderDTO>();

    private bool IsLoading { get; set; } = true;

    public async Task SearchDate()
    {

        Orders =  await _orderRepository.GetDate(DateValue);
    }
    private async Task LoadOrders()
    {
        IsLoading=true;
        StateHasChanged();
        await SearchDate();
        
        //Orders = await _orderRepository.GetDate(date);
        IsLoading = false;
        StateHasChanged();
    }

And Here

public async Task<IEnumerable<OrderDTO>> GetDate(DateTime date)
    {
            if (date != null)
            {
                return _mapper.Map<IEnumerable<Order>, IEnumerable<OrderDTO>>
                   ((IEnumerable<Order>)_db.Orders.Where(u => u.DeliveryDate == date));
            }
            else
            {
                return _mapper.Map<IEnumerable<Order>, IEnumerable<OrderDTO>>(_db.Orders);
            }
        }

For now, the display is something like this

|Driver Name          | Number Delivery Orders |
| :---                |    :----:   | 
| 1                   | 1  |
| 1                   | 1  |
| 2                   | 1  |
|Kim1                 | 4  |

And I want to display like this

|Driver Name          | Number Delivery Orders |
| :---                |    :----:   | 
| 1                   | 2 (Occurrences)  |
| 2                   | 1 (Occurrences)  |
|Kim1                 | 1 (Occurrences)  |

I know that now the Count() Method is counting the length of the driver's name, but how do I code it such that it will return the occurrences of the driver's name.

Thank you guys.

CodePudding user response:

@foreach(var objOrders in Orders
    .GroupBy(u => u.Driver.FullName)
    .Select(group => new {
        Count= group.Count(),
        Key=group.Key }
    )
)

Manage to do it with this. Thanks to @Martin Costello

  • Related