我有一个DTO集合,我希望通过嵌套DTO中某些值的总和来进行排序。
分层结构如下:
它是QuestionDTO的碰撞。
一个QuestionDTO有很多答案都有很多选票。
简而言之:
1 QuestionDto:QuestionID,QuestionTitle,ANSWERS:AnswerId,Answer,VOTES:VoteId,AnswerId,Value
它是我想要为每个答案求和的最后一个值,然后按这个总和为每个问题排序。在列表顶部制作最受欢迎的问题/答案。
提前致谢
答案 0 :(得分: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);
您的课程就像这些
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>();
}
答案 1 :(得分: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);
如您所见,投票总结为Answer
和Question
两个等级,并按降序排列。