在 linq 中使用 let 运算符作为间隔

发布于 2025-01-02 15:21:41 字数 348 浏览 2 评论 0原文

请考虑此图像:

在此处输入图像描述

我有一个像这样的表:

 Age              Active            Men/Women
 -------------------------------------------------

我想使用 linq toEntity 编写一个查询计算男性和女性每个年龄间隔的计数。我可以使用 let 运算符来计算单行,但我想在一个查询中计算 All。

谢谢

please consider this image:

enter image description here

I have a table like this:

 Age              Active            Men/Women
 -------------------------------------------------

I want to write a query with linq to entities that calulate Count of every age intervals for men and women. I canusing let operator to calculate single row but I want to calculat All in one query.

thanks

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

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

发布评论

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

评论(2

苍景流年 2025-01-09 15:21:41

我认为这在 Linq2Sql 中是不可能的,但我想出了这个查询:

Func<int, string> ageGroup = age => string.Format("Age {0}-{1}", (age / 5) * 5, ((age / 5) * 5) + 4);
var blub = from row in table.AsEnumerable()
           where row.IsActive == 1
           group row by ageGroup(row.age)
           into grouped
           from g in grouped
           let menCount = g.Aggregate(0, (sum, r) => sum + r.men)
           let womenCount = g.Aggregate(0, (sum, r) => sum + r.women)
           let totalCount = menCount + womenCount
           select new { AgeGroup = g.Key, Men = menCount, Women = womenCount, Total = totalCount}

首先,我定义一个函数来返回给定年龄的 AgeGroup((age / 5) * 5 给出起始值年龄组的编号)。从那里开始就非常简单了。对年龄进行分组并将数字相加。

编辑:
我认为在一次查询中这是不可能的。因为group by结束了一个查询(如select),所以你需要先分组,然后再相加。
您不能使用 IQueryable,因为 SQL 中不知道 ageGroup() 函数,因此不能在 Linq2Sql 中使用。

I don’t think this is possible in Linq2Sql, but I came up with this Query:

Func<int, string> ageGroup = age => string.Format("Age {0}-{1}", (age / 5) * 5, ((age / 5) * 5) + 4);
var blub = from row in table.AsEnumerable()
           where row.IsActive == 1
           group row by ageGroup(row.age)
           into grouped
           from g in grouped
           let menCount = g.Aggregate(0, (sum, r) => sum + r.men)
           let womenCount = g.Aggregate(0, (sum, r) => sum + r.women)
           let totalCount = menCount + womenCount
           select new { AgeGroup = g.Key, Men = menCount, Women = womenCount, Total = totalCount}

First I define a Function to return the AgeGroup for a given age((age / 5) * 5 gives the starting number for a AgeGroup). From there it’s pretty straightforward. Grouping the ages and add up the numbers.

Edit:
I don’t think it’s possible in one query. Because group by ends a query(like select) and you need to group first and then add up.
You can’t use IQueryable, because the ageGroup() Function is not know in SQL and therefore can’t be used in Linq2Sql.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文