简体   繁体   English

带有日期范围的LINQ查询

[英]LINQ query with date ranges

in my DB i have the following table: 在我的数据库中,我有下表:

name, date_start, date_end, value
test1, 01.01.2019, 05.01.2019, 10
test2, 03.01.2019, 06.01.2019, 11

Now i want to select the rows as the following result: 现在,我想选择以下结果行:

name, date, value
test1, 01.01.2019, 10
test1, 02.01.2019, 10
test1, 03.01.2019, 10
test1, 04.01.2019, 10
test1, 05.01.2019, 10
test2, 03.01.2019, 11
test2, 04.01.2019, 11
test2, 05.01.2019, 11
test2, 06.01.2019, 11

The result must be for every day, one entry with the same values. 结果必须是每天一次,每个条目具有相同的值。 Could anyone help me? 有人可以帮我吗?

Tanks 战车

This wouldn't really be a DB operation, but probably best served in memory. 这实际上不是数据库操作,但最好在内存中使用。

var records = context.data.ToList(); // Add Where clause for boundary..

var byDate = records.SelectMany(x => Enumerable.Range(0, 1 + (int)x.date_end.Subtract(x.date_start).TotalDays)
    .Select(d => new { x.Name, Date = x.date_start.AddDays(d), x.Value })).ToList();

The caveat is that the byDate run needs to be done against memory. 需要注意的是,byDate运行需要针对内存进行。 The first query would be to retrieve the appropriate records containing the date ranges. 第一个查询将是检索包含日期范围的适当记录。 This gets materialized by the ToList() call. 这可以通过ToList()调用实现。 From there we can select a range of dates using Enumerable.Range and compose those with the record Name and Value figures to get an object containing the fields from the record with each applicable date in the range. 在这里,我们可以使用Enumerable.Range选择日期范围,然后将其与记录的名称和值数字组合,以获取一个对象,其中包含记录中具有该范围内每个适用日期的字段。 This example uses an anonymous type for the result, but you can easily substitute that with a view model. 本示例对结果使用匿名类型,但是您可以轻松地用视图模型替换它。

a different approach on @StevePy 's answer, it will still be executed on memory. @StevePy答案的另一种方法,它仍将在内存中执行。

public class ReturnClass
{
    public string name {get; set;}
    public DatTime date {get; set;}
    public string/int value {get; set;}
}

var records = context.data.ToList();

var results = new List<ReturnClass>();

foreach(var record in records)
{
    var date = record.date_start;
    while(date <= record.date_end)
    {
        results.Add(new ReturnClass
        {
            name = record.name,
            date = date,
            value = record.value
        }
        date = date.AddMonths(1);
    }
}

return results;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM