如何生成日期范围值. [英] How to generate a range of date values.

查看:96
本文介绍了如何生成日期范围值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否可以使用一些LINQ魔术来生成一个IEnumerable,该IEnumerable在两个日期之间的每一天都包含一个DateTime?目前,我正在使用循环,但是看起来很笨拙.

Is there not some LINQ magic that I could use to generate an IEnumerable comprising one DateTime for each day between two dates? Currently I''m using a loop, but it just seems clumsy.

推荐答案

不,没有神奇的LINQ方法可以调用我知道的方法的. Enumerable.Range()方法仅使用整数.

我很确定Range()方法仅使用一个循环,在工作表下方使用yield return.我不认为还有其他解决方法.因此,这样简单的事情就足够了.您可以添加类似的方法来根据所需的时间单位来创建范围.

No, there''s no magical LINQ method to call that I''m aware of. The Enumerable.Range() method only uses integers.

I''m pretty sure that the Range() method just uses a loop with yield return underneath the sheets. I don''t believe there''s any other way around it. As such, something as simple as this should suffice. You can add similar methods to create ranges by whatever unit of time you want.

public class DateTimeEnumerable
{
    public static IEnumerable<DateTime> RangeDays(DateTime startDate, DateTime endDate)
    {
        DateTime currentDate = startDate;
        while (currentDate < endDate)
        {
            currentDate = currentDate.AddDays(1);
            yield return currentDate;
        }
    }
}


IMHO LINQ用于查询数据或从现有集合中创建一个可枚举的对象.因此,我认为不应该在这里使用LINQ.

BK:啊,但是我想查询一个包含两个值的集合,并接收一个集合作为响应,一个具有原始两个值以及它们之间所有整数值的集合.
IMHO LINQ is for querying data or creating one enumerable from an existing collection. Hence I believe LINQ should not be used here.

BK: Ah, but I want to query one collection, with two values in it, and receive a collection as a response, one with the original two values and all integral values between them.


同样,您尝试通过LINQ创建"某些东西,恕我直言,这并不是LINQ存在的目的.

我只知道有关通过LINQ创建值的事情是Range方法,该方法已在另一篇文章中介绍过.
Again, you are trying to "create" something through LINQ which, IMHO, is not the purpose why LINQ exists.

Only thing which I know about creating values through LINQ is Range method which already is told in the other post.


这篇关于如何生成日期范围值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆