C# Linq 按 DateTime 分组忽略小时和分钟

发布于 2024-12-04 05:25:44 字数 120 浏览 2 评论 0原文

我有一个 SortedList,其中 DateTime 作为键,int 作为值。 DateTime 值将附加小时和分钟。是否可以编写一个 C# linq 过程来按单个日期对 SortedList 进行分组,忽略小时并对值求和?

I have a SortedList that has DateTime for the key and int for the value. The DateTime value will have the hour and minute attached. Is it possible to write a C# linq procedure to group the SortedList by a single Date ignoring the hour and sum-up the value?

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

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

发布评论

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

评论(2

蓝梦月影 2024-12-11 05:25:44

使用 LINQ 就非常简单了:

from item in list
group item by item.Key.Date into g
select new 
{
   Sum = g.Sum(a => a.Value),
   Values = g
};

With LINQ it is pretty straightforward:

from item in list
group item by item.Key.Date into g
select new 
{
   Sum = g.Sum(a => a.Value),
   Values = g
};
梓梦 2024-12-11 05:25:44

通过单一日期?

简单的!

假设您已将变量 singleDate 声明为 DateTime 来获取总和,以下是查询:

var result = (
        from key in sortedList.Keys.Cast<DateTime>()
        where key.Date == singleDate.Date
        select (int)sortedList[key]
    ).Sum();

我使用 singleDate.Date 来删除 singleDate 可能具有的任何时间信息,但除此之外,这应该相当简单。

SortedList 使用 LINQ 有点痛苦。你能告诉我你为什么使用它吗?

By a single date?

Easy!

Assuming you have declared the variable singleDate as a DateTime to get the sum of, here is the query:

var result = (
        from key in sortedList.Keys.Cast<DateTime>()
        where key.Date == singleDate.Date
        select (int)sortedList[key]
    ).Sum();

I've used singleDate.Date to drop any time information that singleDate may have, but otherwise this should be fairly straight forward.

SortedList is a little painful to work with LINQ. Can you tell me why you are using it?

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