开发者

Help with simple Linq count statement

开发者 https://www.devze.com 2023-02-22 09:34 出处:网络
var q = dc.tblHelpCentreQuestions.Where(c => c.userID == UserID); q.OrderByDescending(c => c.dateSubmitted);
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()};
0

精彩评论

暂无评论...
验证码 换一张
取 消