Linq 计数麻烦

发布于 2024-12-10 16:46:46 字数 446 浏览 0 评论 0原文

我有两个表:

tblBadge
-------
ID
Name

tblBadgeUsers
-------
BadgeID
UserID

一个用户可以有多个徽章,所有关系都在 SQL 数据库中正确设置。

我正在尝试返回用户拥有的所有徽章的列表以及这些徽章的总数。这是我所能得到的,我很困惑。我想返回 tblBadge 数据以及显示授予的徽章总数的额外列。

这不起作用,但这是我的尝试:

var q = db.tblBadgeUsers
    .Where(c => c.UserID == UserID)
    .GroupBy(c => c.BadgeID)
    .Select(c => new { BadgeCount = c.Count(), Record = c.tblBadge });

I have two tables:

tblBadge
-------
ID
Name

tblBadgeUsers
-------
BadgeID
UserID

A user can have many badges, all the relationships are set up properly in the SQL database.

I'm trying to return a list of all the badges a user has, along with the total number of those badges. This is about as far as I can get, I'm getting pretty confused. I want to return the tblBadge data along with an extra column showing the total of that badge awarded.

This doesn't work but is my attempt:

var q = db.tblBadgeUsers
    .Where(c => c.UserID == UserID)
    .GroupBy(c => c.BadgeID)
    .Select(c => new { BadgeCount = c.Count(), Record = c.tblBadge });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼波传意 2024-12-17 16:46:46

鉴于徽章确实具有徽章 ID 和用户,听起来您只需要获取徽章 ID 和该徽章的数量即可使用 - 这意味着只需获取该徽章的密钥即可组:

var q = db.tblBadgeUsers
    .Where(c => c.UserID == UserID)
    .GroupBy(c => c.BadgeID)
    .Select(c => new { BadgeCount = c.Count(), BadgeId = c.Key });

如果有关于每个徽章的更多信息,您可能想要执行以下操作:

var q = db.tblBadgeUsers
    .Where(c => c.UserID == UserID)
    .GroupBy(c => c.BadgeID)
    .Select(c => new { BadgeCount = c.Count(), BadgeId = c.Key, Badges = c });

那么您可以执行以下操作:

foreach (var badgeType in q)
{
    Console.WriteLine("{0}: {1}", badgeType.BadgeId, badgeType.BadgeCount);
    foreach (var badge in q.Badges)
    {
        // Deal with the badge information
    }
}

Given that a badge only really has a badge ID and a user, it sounds like you just need to get the badge ID and the count of that badge for the use - which means just getting the key for the group:

var q = db.tblBadgeUsers
    .Where(c => c.UserID == UserID)
    .GroupBy(c => c.BadgeID)
    .Select(c => new { BadgeCount = c.Count(), BadgeId = c.Key });

If there's more information on each badge, you might want to do:

var q = db.tblBadgeUsers
    .Where(c => c.UserID == UserID)
    .GroupBy(c => c.BadgeID)
    .Select(c => new { BadgeCount = c.Count(), BadgeId = c.Key, Badges = c });

Then you could do:

foreach (var badgeType in q)
{
    Console.WriteLine("{0}: {1}", badgeType.BadgeId, badgeType.BadgeCount);
    foreach (var badge in q.Badges)
    {
        // Deal with the badge information
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文