0

What is the equivalent in LINQ of SqlFunctions.DateDiff so that the code below can be ported?

public class OHLC
{
    public string Symbol { get; set; }
    public System.DateTime Date { get; set; }
    public double Open { get; set; }
    public double High { get; set; }
    public double Low { get; set; }
    public double Close { get; set; }
    public long Volume { get; set; }
}

public enum DateGroupType
{
    Day,
    Week,
    Month,
    Quarter,
    Year
}

private IEnumerable<IGrouping<int?, OHLC>>
GroupByDate(IEnumerable<OHLC> data, DateGroupType group, DateTime startDate)
{
    switch (group)
    {
        case DateGroupType.Day:
            return data.GroupBy(x => SqlFunctions.DateDiff("dd", startDate, x.Date));

        case DateGroupType.Week:
            return data.GroupBy(x => SqlFunctions.DateDiff("ww", startDate, x.Date));

        case DateGroupType.Month:
            return data.GroupBy(x => SqlFunctions.DateDiff("mm", startDate, x.Date));

        case DateGroupType.Quarter:
            return data.GroupBy(x => SqlFunctions.DateDiff("qq", startDate, x.Date));

        case DateGroupType.Year:
            return data.GroupBy(x => SqlFunctions.DateDiff("yy", startDate, x.Date));

        default:
            throw new NotSupportedException($"Grouping by '{group}' is not supported");
    }
})
Ivan
  • 7,448
  • 14
  • 69
  • 134
  • https://stackoverflow.com/questions/62581430/entity-framework-core-how-can-i-use-datediff-in-linq – Renat Nov 19 '22 at 19:19
  • I don't see how that link helps? What do those "dd", "ww" do? And where is that discussed in your referenced link to the other SOF post? – Ivan Nov 19 '22 at 19:37
  • Entity Framework 6 is the old EF6. Not core. If you want to port to EF core, use ef-core-6.0 as tag. And then the answer above *is* your answer. Notice the method names, that remove the datapart parameters from the method calls. – Gert Arnold Nov 19 '22 at 19:50
  • I don't want to port to any version of EF. I want all this to work in plain old C# & Linq – Ivan Nov 19 '22 at 20:32
  • `SqlFunctions` is designed for SQL translation. In plain LINQ you have to use the equivalent `DateTime` methods. The function of these datepart paramaters can be found in the (SQL) DATEDIFF documentation. – Gert Arnold Nov 19 '22 at 22:51

0 Answers0