2017-08-11 47 views
1

我有一個對象數組,我想通過嵌套在每個對象內的公共屬性對它們進行分組。因爲我有麻煩去解釋它,我將發佈對象的類JSON表示:通過公共字段計算嵌套類中的重複對象

reviewList: [{ // review object 
    userObject: {...} 
    content: [ 
     { 
      questionContent: "what sweets do you think John likes?", 
      questionId: 2, 
      answers: [{answer:"Candy"},{answer:"Chocolate"}] 
     }, 
     { 
      questionContent: "Do you like john?", 
      questionId: 3, 
      answers: [{answer:"No"}] 
     } 
    ] 
}, 
{ // review object 
    userObject: {...} 
    content: [ // Questions 
     { 
      questionContent: "what sweets do you think John likes?", 
      questionId: 2, 
      answers: [{answer:"Candy"}] 
     }, 
     { 
      questionContent: "Do you like john?", 
      questionId: 3, 
      answers: [{answer:"Yes"}] 
     } 
    ] 
}] 

我想從這個得到的是看起來很像下面的示例對象的列表:

[{ 
    content: 'what sweets do you think John likes?', 
    answers: [{content: "Candy", count: 2}, {content:"chocolate", count:1}] 
},{ 
    content: 'Do you like john?', 
    answers: [{content: "Yes", count: 1}, {content:"No", count:1}] 
}] 

到目前爲止,我已經嘗試了以下linq代碼,但我真的不知道如何繼續或如果我在正確的道路上。

reviewList 
    .SelectMany(x => x.Questions) 
    .GroupBy(x=>x.QuestionId) 
    .Select(x=>x 
     .ToLookup(y=>y.QuestionContent, y=>y.Answers.ToList()) 
    ) 

我也試圖與ToDictionary代替ToLookup,但我得到重複鍵異常

+0

您不需要SelectMany這可能是您的問題。 GroupBy會做選擇。 – jdweng

+0

我使用SelectMany的原因是從'content'列表中提取所有的問題對象到一個單一的數組中,所以我可以擺脫複習課程,只有列表中的問題。我不確定我如何使用GroupBy來達到相同的效果。 – Zephy

+0

試試這個:reviewList .GroupBy(x => x.QuestionId) .Select(x => x new {question = y => y.QuestionContent,answer = y => y.Answers.ToList()}) .SelectMany(x => x).ToList(); – jdweng

回答

1

這是一個容易得多,如果你使用C#的匿名對象,以顯示你的結構複製/粘貼。無論如何,您需要使用另一個SelectMany來合併答案:

var ans = reviewList.SelectMany(r => r.content).GroupBy(r => r.questionContent).Select(r => new { content = r.Key, answers = r.SelectMany(a => a.answers).GroupBy(a => a.answer).Select(a => new { content = a.Key, Count = a.Count() }) }); 
+0

這工作完美,並做到我想要的。非常感謝 – Zephy