c# - LINQ查询的返回结果

标签 c# linq

刚接触 LINQ,但这应该相当简单。

我正在从数据库中提取产品记录集:

ReportData= topProductsController.GetWowDetails(CurrentUser.UserId, _companyGroupCode, sector, year, string.Empty, string.Empty, string.Empty);

我尝试根据该记录集按产品 ID 和计数对结果进行分组:

var productCounts = (from record in wowReportData
                        group record by record.ProductID into grouping
                                 select new topProduct { Name = grouping.Key, quantity = grouping.Count() });

这是我要返回的类(class):

public class topProduct
{
    public int quantity { get; set; }
    public string Name { get; set; }

    public topProduct(string productDesc, int downloadCount)
    {
        this.Name = productDesc;
        this.quantity = downloadCount;
    }
}

我正在尝试从函数返回这些列表。目前的错误是:

topProduct does not contain a constructor that takes 0 parameters

最佳答案

它失败的原因是因为您正在使用属性初始值设定项方式为属性设置值,并且至少以您调用它的方式(new topProduct {...)它将首先使用默认构造函数初始化对象。但你没有。

更改为:

var productCounts = (from record in wowReportData
                     group record by record.ProductID into grouping
                     select new topProduct(grouping.Key, grouping.Count()));

或者添加一个默认构造函数(这就是我要做的),然后您就可以像以前一样使用它

public class topProduct
{
    public int quantity { get; set; }
    public string Name { get; set; }

    //default constructor
    public topProduct() {}

    public topProduct(string productDesc, int downloadCount)
    {
        this.Name = productDesc;
        this.quantity = downloadCount;
    }
}

当您初始化对象并调用构造函数时使用 () - () 是默认构造函数(不带参数)。如果您尚未创建任何其他构造函数,则会自动创建此构造函数。 See here about constructors .

现在,在 C# 3.5 中,如果我没记错的话,他们引入了在对象初始化时内联初始化属性的能力,从而避免了为所有不同选项创建大量构造函数的痛苦。但这只是一个很好的语法糖:

var obj = new Class() { Prop1 = "a", Prop2 = 2 };
        ||
var obj = new Class();
obj.Prop1 = "a";
obj.Prop2 = 2;

然后他们甚至允许您删除空的 () (如果您调用的构造函数是默认构造函数),结果会得到: var obj = new Class { Prop1 = "a", Prop2 = 2 }; 但如果您没有像原始情况那样的默认构造函数,则无法执行此操作。

关于c# - LINQ查询的返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39039874/

相关文章:

c# - LINQ 复杂查询导航属性

c# - 当与 orderby 一起使用时,是否存在 ascending 关键字纯粹是为了清楚起见?

c# - 如何仅比较 LINQ to Entities 中 TimeSpan 的分钟部分?

c# - 如何让另存为对话框出现 "early"?或者 : How to make Flush() behave correctly?

c# - 系统.Data.SQLite.SQLiteException : unable to open database file

c# - 在 EF Core Linq GroupBy 语句中使用前导零格式化日期

c# - 有没有办法在不添加 .dbml 文件的情况下使用 Linq to SQL?

c# - 无法将类型 'System.Linq.IQueryable<>' 隐式转换为 'Model' 。存在显式转换(是否缺少强制转换?)

C# Visual Studio 数据 GridView 返回 0,其中显示了 SQL 计数

c# - 以匿名类作为数据源的 BindingSource 列