我有一个linq查询,它返回一个未知类型值的列表。我想在方法中包含此查询并使用该方法获取结果
public __________ getResult() {
var result = from ps in _context.PurchasingShipments
group ps by ps.date.Value.Year into grp
select new
{
Year = grp.Key,
Cost = grp.Sum(x => x.NoOfPieces * x.PricePerPiece + x.Micelleneous + x.TransportCost + x.SupplierCommission)
};
return result;
}
上面是一个例子,getResult方法的返回类型应该是什么?请帮忙
答案 0 :(得分:2)
解决方案1:我强烈建议您创建包含属性的模型并返回该模型的列表。
public class CostYearModel {
public int Year { get; set; }
public int Cost { get; set; }
}
方法如下
public List<CostYearModel> getResult() {
var result = from ps in _context.PurchasingShipments
group ps by ps.date.Value.Year into grp
select new CostYearModel
{
Year = grp.Key,
Cost = grp.Sum(x => x.NoOfPieces * x.PricePerPiece + x.Micelleneous + x.TransportCost + x.SupplierCommission)
};
return result.ToList();
}
解决方案2:如果您不能和/或不想为此创建模型,错误解决方案将返回对象列表。您可以使用反射来访问值。
public List<Object> getResult() {
var result = from ps in _context.PurchasingShipments
group ps by ps.date.Value.Year into grp
select (new
{
Year = grp.Key,
Cost = grp.Sum(x => x.NoOfPieces * x.PricePerPiece + x.Micelleneous + x.TransportCost + x.SupplierCommission)
} as Object);
return result.ToList();
}
访问每个属性的值(在您的情况下为Cost和Year)的代码如下所示。
foreach (var costYear in result)
{
var properties = costYear.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var value = property.GetValue(costYear, null);
}
}
答案 1 :(得分:1)
你只能返回对象,你应该创建一个类:
public class CostYearModel{
public int Year {get; set;}
public int Cost {get; set;}
}
public List<CostYearModel> getResult() {
var result = from ps in _context.PurchasingShipments
group ps by ps.date.Value.Year into grp
select new CostYearModel
{
Year = grp.Key,
Cost = grp.Sum(x => x.NoOfPieces * x.PricePerPiece + x.Micelleneous + x.TransportCost + x.SupplierCommission)
};
return result.ToList();
}