刚接触 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/