帮助简单的Linq计数声明

时间:2011-04-04 09:18:39

标签: c# asp.net linq linq-to-sql

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

这样可以正常工作,但我还需要返回从tblHelpCentreReplies返回的记录数,其中QuestionID等于tblHelpCentreQuestions.ID。这对我来说在SQL中很容易,有人能告诉我这是如何在LINQ to SQL中完成的吗?

修改

我已经达到了这个目标:

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() };

但是replies.Count()抛出:

  

无效的匿名类型成员   声明符。匿名类型成员   必须与会员宣布   作业,简单名称或成员   访问。

3 个答案:

答案 0 :(得分:3)

linq查询看起来像这样:

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()});

<强>更新 如果你有一个关系映射,那可能会更容易

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

答案 1 :(得分:1)

这比你想象的要容易: - )

var q = 
    from question in dc.tblHelpCentreQuestions
    where question.userID == UserID
    orderby question.dateSubmitted desc
    select new { question, question.Replies.Count() };

答案 2 :(得分:1)

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()};