基本上我有这门课
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”是带有 Gasto 列表的字符串列表 (TipoGasto)。
¿ 问题(问题)是这个 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() } )
您必须创建另一个具有这两个 Prop 的类。
(或使用 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/