基本上我有这个类(class)
public class Gasto
{
public int IdTienda { get; set; }
public int IdGasto { get; set; }
public System.DateTime Fecha { get; set; }
public string ConceptoDeGasto { get; set; }
public double Total { get; set; }
public string TipoDeGasto { get; set; }
public Nullable<int> IdVenta { get; set; }
public Nullable<System.DateTime> FechaVenta { get; set; }
public virtual Tienda Tienda { get; set; }
}
我正在尝试构建一个像这样的 ViewModelClass
public class CorteConVentas
{
// STILL NO ATRIBUTE -- THIS IS THE QUESTION
}
这是 Controller 的代码,我将在其中构建按 TipoDeGasto 分组的 Gasto 列表
var gastos = db.Gastos.Where(g => g.IdGasto >= corte.DesdeIdGasto && g.IdGasto <= corte.HastaIdGasto).ToList();
var GD = gastos.GroupBy(u => u.TipoDeGasto).Select(grp => new { TipoGasto = grp.Key, gastos = grp.ToList() } ).ToList();
如您所见,变量“GD”是一个字符串列表 (TipoGasto) 和 Gasto 列表。
¿问题是这个 GD 我怎样才能将它声明为我的 viewModelClass 的属性?
我为 ViewModel 尝试了类似的方法
public class CorteConVentas
{
public List<string, List<Gasto>> listaGastosAgrupada { get; set; }
}
但是有一些问题。错误的输出显示:
Using the generic type List requires 1 type arguments
最后,正如 @Ziv Weissman 所说,解决方案是不使用匿名类型
所以我创建了一个这样的类
public class CorteConVentas
{
public List<GastosAgrupados> listaGastosAgrupada { get; set; }
}
public class GastosAgrupados
{
public string TipoGasto { get; set; }
public List<Gasto> gastos { get; set;}
}
然后在 Controller 中创建分组列表时我这样做了
var gastos = db.Gastos.Where(g => g.IdGasto >= corte.DesdeIdGasto && g.IdGasto <= corte.HastaIdGasto).ToList();
var gd = gastos.GroupBy(u => u.TipoDeGasto).Select(grp => new GastosAgrupados { TipoGasto = grp.Key, gastos = grp.ToList()) } ).ToList();
感谢大家对我的帮助。
最佳答案
您不能声明匿名类型的变量:
.Select(grp => new { TipoGasto = grp.Key, gastos = grp.ToList() } )
您必须创建另一个具有这两个属性的类。 (或使用 KeyValuePair)
类似 -
.Select(grp => new KeyValuePair<string,List<Gasto>> { Key = grp.Key, Value = grp.ToList() } )
然后您可以创建一个强类型的 Prop 。
public class CorteConVentas
{
List<KeyValuePair<string,List<Gasto>>> PropName {get; set;}
}
关于c# - 如何按对象列表进行分组并将该列表声明为 View 模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44077672/