0

i have an trouble with lambda expression i have some releated tables and i need to select some results with count and avarage functions here ise the example class

class Course{
public long id;
public string name;
public virtual ICollection<Chapter> chapters;
}

class Chapter{
public long id;
public virtual ICollection<Videos> videos;
public virtual ICollection<Files> files;
}

i need to select them into

select new{
videoCount = [number of video releated to course],
fileCount = [number of file releated to course],
}

how can i select with lambda expression like

var result = from c in Courses...
             i cant figured out here
             select new{
                          videoCount = [number of video releated to course],
                          fileCount = [number of file releated to course],
             };

thanks for your help.

Blockquote

1
  • 1
    Could you show us your Videos and Files class too? Commented Jun 10, 2016 at 13:52

2 Answers 2

2

You have an error in your code: after public virtual ICollection<Chapter> you don't have the property name. I assume it is called Chapters. Same for Videos and Files properties.

Try this:

var result = courses.Select(c => new
{
    videoCount = c.chapters.Sum(chapter => chapter.Videos.Count()),
    fileCount = c.chapters.Sum(chapter => chapter.Files.Count())
});

You Sum the count of videos in each chapter, to get the total for the course.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

var courses = new List<Course>();

courses.Select(x=> new { 
                       VideoCount = x.Chapters.Sum(v=>v.Videos.Count),
                       FilesCount = x.Chapters.Sum(v=>v.Files.Count)
                       });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.