简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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