【问题标题】:Returning a Dictionary from a gouped query从组合查询返回字典
【发布时间】:2012-11-21 05:55:30
【问题描述】:

我的 SQL Anywhere 12.0.1 数据库中有一个表:

CREATE TABLE Entries (
    ListId        UNIQUEIDENTIFIER NOT NULL,
    . . .
);

我需要查询表以获取表中具有相同 ListID 的行数。在 SQL 中:

SELECT ListID, COUNT(*)
FROM Entries
GROUP BY ListId;

我想使用 Entity Framework 4.x 执行此查询,并且我想将结果作为 Dictionary<Guid, long> 返回。像这样的:

public Dictionary<Guid, long> GetRowCounts( MyEntities context ) {
    Dictionary<Guid, long> result = null;
    try {
        result = ( from entry in Entries
                   group entry by entry.ListId into listGroup
                   select listGroup ).ToDictionary( grp => grp.Key, ???? );

    } catch ( Exception ex ) {
        . . .
    }
    return result;
}

请记住,我想要返回每个唯一 ListId 的行数。我用什么代替“??????”?

【问题讨论】:

    标签: .net entity-framework-4 group-by


    【解决方案1】:

    好吧,看看你写的:

    记住,我想要 count

    (强调我的)。所以你需要:

    ToDictionary(grp => grp.Key, grp => grp.Count())
    

    我个人会写这样的方法:

    public Dictionary<Guid, int> GetRowCounts(MyEntities context) {
        return context.Entries
                      .GroupBy(entry => entry.ListId)
                      .ToDictionary(g => g.Key, g => g.Count());
    }
    

    ...或者如果您仍然希望它是 Dictionary&lt;Guid, long&gt;,请使用 g =&gt; g.LongCount(),或者直接转换:

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

    您几乎肯定不希望出现 try/catch 块,直接返回要简单得多。同样,除非您正在编写一个中等复杂的查询,否则使用查询表达式确实没有任何好处。也学习直接使用扩展方法,以便为每个查询编写尽可能简单的代码。

    【讨论】:

    • 我试过了;它不会编译。现在我看了一下,错误是您无法将Dictionary&lt;Guid, int&gt; 转换为Dictionary&lt;Guid, long&gt;。我想我会将 Dictionary 的值的类型更改为 int。谢谢。
    • @TonyVitabile:要么,要么使用LongCount()。我将编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多