c# - 使用 c# Func 作为 IQueryable 的一部分而不执行内存调用

标签 c# linq func

我正在尝试构建一个将作为 IQueryable 而不是在内存中 (IEnumerable) 针对数据库执行的查询。

查询将用于几个不同的目的,每个目的计算 Total 属性的方式略有不同。

因为我正在使用 Func 来计算总数,所以我得到一个错误提示我 sql 不知道如何处理我的 Func 的 Invoke 方法,这是可以理解的。

为了解决这个问题,我不得不通过调用 ToList() 将分组列出到内存中,这对性能不利。

有没有一种方法可以将此查询作为 IQueryable 执行?否则我将不得不使用计算方差编写此查询 20 多次

Func<IGrouping<object, MyType>, double?> calculateTotal= (group) => @group.Sum(x => x.PassengerTotal);

Dictionary<object, double?> weekValues = queryable.GroupBy(o => new
               {
                   Year = SqlFunctions.DatePart("yyyy", o.DateCreated),
                   Week = SqlFunctions.DatePart("ww", o.DateCreated),
                   Source = o.SourceId,
               })
               .ToList() //NEED TO REMOVE THIS CALL
               .Select(ac => new WeeklyGraphGroup()
               {
                   Year = ac.Key.Year,
                   Week = ac.Key.Week,
                   SourceId = ac.Key.Source,
                   Total = calculateTotal(ac)
               })
               .ToDictionary(dict =>
                   new
                   {
                       Year = dict.Year,
                       Week = dict.Week,
                       Source = dict.SourceId
                   }, grp => grp.Total);

最佳答案

创建一个分部类如下:

public partial class WeeklyGraphGroup
{
    public int ? Year { get; set; }

    public int  ? Week { get; set; }

    public int Source { get; set; }

}

public partial class WeeklyGraphGroup
{
    private int ? _Total;

    public int ? Total
    {


        get
        {


            this._Total = CalculateTotal(this.Year, this.Week, this.Source);

            return this._Total;
        }

    }

    public int ? CalculateTotal(int ? Year, int ? Week, int Source)
    {

        // do your calculation and return the value of total
        // use whatever formula you want here. I guess you are calculating 
        // total based on any of the parameters(year, week or source);

        return value;

    }



}

然后按如下方式查询:

var list = db.Stores.GroupBy(o => new WeeklyGraphGroup
{
Year = SqlFunctions.DatePart("yyyy", o.DateCreated),
Week = SqlFunctions.DatePart("ww", o.DateCreated),
Source = o.SourceId,
})
.Select ( u => new WeeklyGraphGroup 
{
Year = u.Key.Year,
Week = u.Key.Week,
Source = u.Key.Source
}
).ToList();

总数会自动更新

关于c# - 使用 c# Func 作为 IQueryable 的一部分而不执行内存调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42067722/

相关文章:

c# - WPF PropertyChanged 代码错误 : cannot implement 'System. ComponentModel.INotifyPropertyChanged

c# - ExpressMapper - 映射/克隆枚举 - InvalidCastException

c# - 如何在 C# 中使用包含 '-' 字符的列的 LINQ?

c# - 如何按字母分组并放入相同的字母大小

swift - #selector 与闭包不兼容?

c# - 缩小 Azure Web 应用程序时打开套接字会发生什么情况?

c# - 使用 Team City 构建 ASP MVC 解决方案时出错

.net - Linq 的聚合函数,如何制作 CSV 字符串

c# - 为什么编译器将 Func<dynamic, int> 的返回类型视为强类型?

c# - 在 C# 中使用 Dictionary<T, Func<List, bool>> 查找列表中最常见的事件