简体   繁体   中英

Help with simple Linq count statement

var q = dc.tblHelpCentreQuestions.Where(c => c.userID == UserID);
q.OrderByDescending(c => c.dateSubmitted);

This works fine, but I also need to return the count of records returned from tblHelpCentreReplies where QuestionID equals tblHelpCentreQuestions.ID . This is easy enough for me in SQL, can someone show me how this is done in LINQ to SQL?

Edit

I've got as far as this:

var q = 
from question in dc.tblHelpCentreQuestions
join replies in dc.tblHelpCentreReplies on question.ID
    equals replies.ticketID
where question.userID == UserID
orderby question.dateSubmitted descending
select new { question, replies.Count() };

But replies.Count() throws:

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

the linq query would look like this:

var q =
    dc.tblHelpCentreQuestions.
        Where(question => question.userID == UserID).
        OrderByDescending(question => question.dateSubmitted).
        GroupJoin(
            dc.tblHelpCentreReplies,
            question => question.ID,
            replies => replies.ticketID,
            (question, replies) => new {Question = question, RepliesCount = replies.Count()});

update if you have a relation mapping than that could be a bit easier

var q =
    dc.tblHelpCentreQuestions.
        Where(question => question.userID == UserID).
        OrderByDescending(question => question.dateSubmitted).
        Select(question => new {Question = question, RepliesCount = question.Replies.Count()});

This is easier than you might imagine :-)

var q = 
    from question in dc.tblHelpCentreQuestions
    where question.userID == UserID
    orderby question.dateSubmitted desc
    select new { question, question.Replies.Count() };
var q = 
from question in dc.tblHelpCentreQuestions
join replies in dc.tblHelpCentreReplies on question.ID equals replies.ticketID
where question.userID == UserID
orderby question.dateSubmitted descending
select new { Question = question, RepliesCount = replies.Count()};

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