c# - 如何按对象列表分组并将此列表声明为 View 模型的属性

标签 c# asp.net asp.net-mvc linq

基本上我有这门课

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



这是分组后的输出
enter image description here

最后,@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/

相关文章:

c# - 保持在表格右下角的按钮

javascript - 如何使用带有类的 Jquery 从动态创建的复选框中获取值

c# - 使用 ASP.Net MVC 在单一 View 中管理多个查找

c# - C# 中的集合

c# - 静态枚举类的 Msbuild.exe 错误

c# - 如何在asp.net中只创建一次类的实例

c# - 在 POST 操作中的模型中将 DropDownList 选定值设置为 "null"

c# - 如果无法选择Mysql,则使用Mysql数据库替代方案

c# - IsNullorEmpty combobox.selectedvalue

asp.net - 页面上有多个 RequiredFieldValidator 但它们需要应用于不同的按钮点击