0

I've got the following SQL Query which provides me with Month, Year and Count. How can I do the equivalent in LINQ Query Syntax?

SQL

SELECT 
    MONTH(ExpiryDate) MONTH, 
    YEAR(ExpiryDate) YEAR, 
    COUNT(*) COUNT 
FROM tblItems 
GROUP BY 
    YEAR(ExpiryDate), 
    MONTH(ExpiryDate)

Thanks in advance

[UPDATE WORKING ANSWER]

var query = from a in db.tblItems
                                       group a by new
                                       {
                                           ((DateTime)a.ExpiryDate).Year,
                                           ((DateTime)a.ExpiryDate).Month
                                       } into bca
                                       select new
                                       {
                                           MonthField = bca.Key.Month,
                                           YearField = bca.Key.Year,
                                           CountField = bca.Count(),
                                       };
1
  • LINQ is too broad. Please provide more context - LINQ to SQL, LINQ to Entities (EF, EF Core, which version) etc. Commented Jun 20, 2017 at 16:34

2 Answers 2

1

Please try this:

var info =  from a in tblItems
            group a by new
            {
                a.ExpiryDate.Year,
                a.ExpiryDate.Month
            } into bca
            select new ConsolidatedData()
            {
                MonthField = bca.Key.ExpiryDate.Month,
                YearField = bca.Key.ExpiryDate.Year,
                CountField = bca.Count(),
            };

You can also try LINQPad to develop your skills in LINQ, You already have the SQL logic. Have a nice day

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

1 Comment

Thanks for this I've got it working with some minor changes. I've updated the question with my answer. Also thanks for the link to LINQPad didn't know that existed.
0

I did not exactly understand what you were asking for but I would use grouping in linq like this.

'from item in tblItems 
group item by year,month into group select group.firstordefault.month,group.firstordefault.year,group.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.