【问题标题】:Count Number of rows in table using lambda expression [closed]使用 lambda 表达式计算表中的行数
【发布时间】:2021-04-11 18:36:57
【问题描述】:

我是编程新手,谁能帮帮我...

<div>
    <h5>Total Number of Classes = @Model.Count(i => i.Class_ID)</h5>
</div>

如何解决这个问题.. 下图显示了错误错误 cs1662 和 cs0029

这是模型

// 命名空间 School_ManagementSystem.Models {

[Table("Tbl_Class")]

public class ClassModel
{
    [Key]
    [DisplayName("Class ID")]
    public string Class_ID { get; set; }

    [Required(ErrorMessage = "Please Select a Lecturer")]
    [DisplayName("Lecturer")]
    public string Lecturer { get; set; }

    [Required(ErrorMessage = "Please Select the Start Date.")]
    [DisplayName("Start Date")]
    public DateTime Start_Date { get; set; }


    [Required(ErrorMessage = "Please Select the End Date.")]
    [DisplayName("End Date")]
    public DateTime End_Date { get; set; }

    [Required(ErrorMessage = "Please Provide a Valid Student Count")]
    [DisplayName("Student Limit")]
    public int Student_Count { get; set; }


    [Required(ErrorMessage = "Please Select a Status.")]
    [DisplayName("Status")]
    public string Status { get; set; }

    [Required(ErrorMessage = "Please Select a Course.")]
    [DisplayName("Course")]
    public string Course_ID { get; set; }

    [Required(ErrorMessage = "Please Select a Subject.")]
    [DisplayName("Subject")]
    public string Subject_ID { get; set; }

}

}

【问题讨论】:

  • 你的模型是什么样的?

标签: c# html asp.net-mvc asp.net-core razor-pages


【解决方案1】:

Count LINQ 函数计算 lambda 计算结果为 TRUE 的行数。

// Count the number of records where the column is equal to 5
@Model.Count(x => x.SomeNumber == 5);
// Count the number of rows where some text contains some other text
@Model.Count(x => x.SomeText.Contains(“Something”));

错误告诉您,您的 lambda 不会评估为布尔值,因为 i.Class_ID 只是一个属性。

如果你想计算不同类的数量,你应该使用 CountDistinct:

@Model.CountDistinct(x => x.Class_ID);

如果你想知道类的数量而不考虑重复,你不应该传递一个 lambda:

@Model.Count();

【讨论】:

  • 非常感谢...“S. Walker”成功了
  • 我也不明白为什么这个问题被关闭了。对我来说似乎相当详细。
  • 非常感谢...@S。沃克它起作用了..我想要这个@Model.Count();此外,我如何添加 where 子句,例如(Get Count where Status == "Active")
  • @Model.Count(x => x.Status == “活动”)
  • 非常感谢@S。沃克......你的答案奏效了......我也找到了这样的方法 @Model.Where(m => m.Status == "Active").Count() 多亏了你......上帝保佑跨度>
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多