DotnetSparrow
DotnetSparrow

Reputation: 27996

Linq query with one to many relation

I have two entites in my asp.net MVC3 application and I am using EF 4.1. Entities are:

public class Category {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Movie> Movies { get; set; }
}

public class Movie {
    public int Id { get; set; }
    public string Title { get; set; }
    public string Director { get; set; }
    public int Price {get; set;}
    public DateTime ReleaseDate { get; set; }
    public string Description { get; set; }
    public Category Category { get; set; }
}

I want to calculate sum of prices of all movies where category name = "Comedy" using Linq query. Can you please suggest me Linq query using extension method ?

Thanks.

Upvotes: 0

Views: 432

Answers (1)

smartcaveman
smartcaveman

Reputation: 42246

Assuming that you have an IEnumerable<Movie> movies, you can do

movies
    .Where(x => x.Category.Name == "Comedy")
    .Select(x => x.Price)
    .Sum();

As @Linkgoron says in the comment, you can also put the predicate in the Sum method, such as:

movies
    .Where(x => x.Category.Name == "Comedy")
    .Sum(x => x.Price);

Upvotes: 1

Related Questions