C# 方法返回未知类型的列表

C# 方法返回未知类型的列表,c#,linq,C#,Linq,我有一个linq查询,它返回未知类型值的列表。我想将此查询包含在一个方法中,并使用该方法获取结果 public __________ getResult() { var result = from ps in _context.PurchasingShipments group ps by ps.date.Value.Year into grp select new {

我有一个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方法的返回类型应该是什么?请帮助

您只能返回对象,您应该创建一个类:

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();
}
公共类成本模型{
公共整数年{get;set;}
公共整数成本{get;set;}
}
公共列表getResult(){
var结果=来自_context.PurchasingShipments中的ps
按ps.date.Value.Year将ps分组到grp中
选择新模型
{
年份=grp.键,
成本=总成本(x=>x.NoOfPieces*x.单价+x.胶束+x.运输成本+x.供应商佣金)
};
返回result.ToList();
}

解决方案1:I强烈建议您创建一个包含属性的模型,并返回该模型的列表

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();
}

您正在
select
语句中创建匿名类型,因此
result
将是匿名类型的可枚举项。返回该值的唯一方法是将其作为
IEnumerable
,但是如果这样做,您将如何在
getResult
方法之外使用它?您最好创建一个包含这两个字段的特定结果类型(类)。您可能需要将
CustomClass
更改为
CostYearModel
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();
}
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);
    }
}