繁体   English   中英

从对象列表中检索计数

[英]Retrieving count from a list of objects

我有一个评论列表作为我网站上每节课的参数。 我尝试了许多不同的方法(如下所示)来检索注释的数量。 我的模型的结构如下所示:

 public class EducateLesson
{
    [Key]
    public int EducateLessonID { get; set; }

    public EducateTopics Topic { get; set; }

    public string Title { get; set; }

    public string Introduction { get; set; }

    public string Body { get; set; }

    public string VideoURL { get; set; }

    public int Likes { get; set; }

    public virtual List<Comment> Comments { get; set; }

    public void AddComment(Comment c)
    {
        Comments.Add(c);
    }
}

public class Comment
{
    [Key]
    public int CommentID { get; set; }
    public DateTime Date { get; set; }
    public string IdentityUserName { get; set; }
    public string Text { get; set; }
}

我注意到Comment类在这里没有FK到课程对象。

这些是我尝试检索视图中单个课程计数的方法:

count = (from l in lesson.Comments select l).Count();
@lesson.Comments.Count()
@lesson.Comments.Count

我在不改变模型的情况下解决了这个问题 对这篇文章的评论实际上并不有益。 首先,我将其添加到我的存储库类:

   public int CommentCount(int id)
    {
        EducateLesson lesson = context.EducateLessons.Find(id);
        return lesson.Comments.Count;
    }

接下来,我通过创建一个存储库类并对每个课程对象使用此方法来计算:

    int count = 0;
    EducateRepository EducateRepository = new EducateRepository();

    count = EducateRepository.CommentCount(lesson.EducateLessonID);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM