简体   繁体   English

从对象列表中检索计数

[英]Retrieving count from a list of objects

I have a list of comments as a parameter to each lesson on my website. 我有一个评论列表作为我网站上每节课的参数。 I have tried a number of different ways (shown below) to retrieve the number of comments. 我尝试了许多不同的方法(如下所示)来检索注释的数量。 The structure of my Model looks like this: 我的模型的结构如下所示:

 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; }
}

I have noted that the Comment class has no FK to the lesson object here. 我注意到Comment类在这里没有FK到课程对象。

These are the methods I've tried to retrieve the count for an individual lesson in the view: 这些是我尝试检索视图中单个课程计数的方法:

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

I solved this answer without changing the model. 我在不改变模型的情况下解决了这个问题 Comments made on this post were not actually beneficial. 对这篇文章的评论实际上并不有益。 Firstly I added this to my repository class: 首先,我将其添加到我的存储库类:

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

Next I took the count by creating a repository class and using this method for each lesson object: 接下来,我通过创建一个存储库类并对每个课程对象使用此方法来计算:

    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