2014-07-25 91 views
0

得到總和和順序我有一個DTO的集合,我想在其中嵌套DTO中的某些值的總和進行排序。IQueryable通過子集

的hiearchy如下:

其QuestionDTO的的collction。

QuestionDTO有許多答案,其中有很多投票。

因此,在短期:

1 QuestionDto:QuestionID,QuestionTitle,回答:AnswerId,答案,投票數:VoteId,AnswerId,價值

它,我想歸納每個答案的最後一個值,然後按每個問題的總和排序。在列表頂部製作最受歡迎的問題/答案。

在此先感謝

回答

0

我想你想要這樣的:

var questionList = new List<Question>();//Get a real list 

    var sortedQuestions = (from i in questionList 
          select new 
            { 
             i.QuestionID, 
             i.QuestionText, 
             VotesSum = i.Answers.Sum(ee => ee.Votes.Sum(ss => ss.Value)) 
            } 
          ).OrderByDescending(ee => ee.VotesSum); 

    foreach (var item in sortedQuestions) 
       Console.WriteLine(item.QuestionText + " " + item.VotesSum); 

Asumming你的類是像這些

class Vote 
{ 
    public int VoteID { get; set; } 
    public int Value { get; set; } 

} 
class Answer 
{ 
    public int AnswerID { get; set; } 
    public string AnswerText { get; set; } 
    public List<Vote> Votes = new List<Vote>(); 
} 

class Question 
{ 
    public int QuestionID { get; set; } 
    public string QuestionText { get; set; } 
    public List<Answer> Answers = new List<Answer>(); 
} 
0

這裏有一種方式來獲得你想要的東西:

var query = questions.Select(q => 
     new { q.QuestionText, 
       Answers = q.Answers.Select(a => 
        new { a.AnswerText, 
          Votes = a.Votes.Sum(v => v.Value) 
         }) 
      }) 
     .Select(q => 
      new { q.QuestionText, 
        Votes = q.Answers.Sum(a => a.Votes), 
        Answers = q.Answers.OrderByDescending(a => a.Votes) 
       }) 
     .OrderByDescending(q => q.Votes); 

As你看,票數總結在兩個級別,AnswerQuestion,並按降序排列。