返回计数列表并按 id linq 分组到 sql

Returning list of count and grouped by id linq to sql

我有一个 table 那是电话清单:

public class CHECKLIST{
[Key]
public int CL_ID { get; set; }

public EmpID { get; set; }
}

我正在尝试 return 如下所示的列表。

EMPID   COUNT
1       5
2       7
3       10

我正在尝试将存储库编写为字典,但在 g=> g.Count 出现错误,无法将 lambda 表达式转换为 IEqualityComparer 类型,因为它不是委托类型:

    public Dictionary<int, int> GetAllComplaintsCount()
    {
        try
        {
            return _context.Checklists
                .GroupBy(a => a.MonitorEnteredEmpID)
                .ToDictionary(g => g.Key, g => g.Count);
        }
        catch (Exception ex)
        {
            _logger.LogError("Could not get am with checklist", ex);
            return null;
        }
    }

如果你改变这个:

ToDictionary(g => g.Key, g => g.Count);

以下内容:

ToDictionary(g => g.Key, g => g.Count());

你会得到你想要的。您应该这样做的原因取决于结果 GroupBy returns。根据 specification

The group clause returns a sequence of IGrouping objects that contain zero or more items that match the key value for the group. For example, you can group a sequence of strings according to the first letter in each string. In this case, the first letter is the key and has a type char, and is stored in the Key property of each IGrouping object. The compiler infers the type of the key.

你想要的是获取每个组中的项目数。由于您有一个序列,因此您可以通过调用 Count 方法来获取序列中项目的数量。