This query returns the top 25 best sellers from our database, by customer:
var query = from bs in db.MYDATABASE
where bs.COMPANY == "MY COMPANY"
group bs by bs.PRODCODE into g
orderby g.Sum(x => x.MQTY) descending
select new BestSeller
{
product_code = g.Key,
product_description = g.First().DESCRIPTION,
total_quantity = g.Sum(x => x.MQTY)
};
var top25 = query.Take(25);
I’ve been told in this question that I need to create a projection for the following LINQ query at the following line:
total_quantity = g.Sum(x => x.MQTY)
Please could someone explain what is meant by a projection and examples of such?
Projection is the term used with respect to LINQ when you are selecting few fields from the query and creating / projecting it to a new type. When you are doing
select newin your query, you are actually doing projection. In your case you are selecting fields likeg.Keyandg.First().DESCRIPTIONfrom your query expression and creating a new object of typeBestSeller.Since your original question didn’t has the
total_quantityfield assigned to anything that is why Jon Skeet asked you to add the sum to your projection.You need to see the following articles on MSDN about projection:
Formulate Projections
Query Expression Syntax Examples: Projection