将数据收集转换为嵌套的分层对象列表

时间:2018-10-26 16:18:41

标签: c# linq asp.net-core

我想进行API调用,以获取所有唯一的调查ID,并将其放入具有基于唯一答案值和用户ID列表的总答案计数的数组。例如:ICollection<Survey>

ID Survey_Id       Answer  User
1  Apple_Survey    1       Jones
2  Apple_Survey    1       Smith
3  Banana_Survey   2       Smith
4  Apple_Survey    3       Jane
5  Banana_Survey   2       John

我当前拥有的API结果:

{Data: [
  {
      survey_id: "Apple_Survey",
      answer: "1",
      user: "Jones"
  },
  ...
]}

卡住的地方是代码中处理数据的地方:

foreach (var info in data
                     .GroupBy(x => x.Survey_Id)
                     .Select(group => new { SurveyId = group.Key, 
                                          Count = group.Count() }) )
{
    Console.WriteLine("{0} {1}", info.SurveyId, info.Count); 
    //Result: Apple_Survey 3 Banana_Survey 2
}

理想的结果:

{Data: [
  {
      survey_id: "Apple_Survey",
      answers: [//Example: rating answer would be 1-10, not an ID
             {answer: "1", count: 2, users: ["Jones", "Smith"]},
             {answer: "3", count: 1, users: ["Jane"]}
      ]
   },
   ...
]}

如何根据Survey_id获得不同的答案,并根据答案获得用户列表?任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:0)

一种简单的方法仅基于sql。您可以将查询用作:

select Survey_Id, Answer, COUNT(*)  answer_count, group_concat(user) answer_user
from my_table  
group  Survey_Id, Answer

答案 1 :(得分:0)

我会去

table.GroupBy( x => x.Survey_Id ).Select( x => new { Survey_Id=x.Key, Answers=x.GroupBy( y => y.Answer ).Select( y => new { Answer=y.Key, Count=y.Count(), Users=y.Select( z => z.User)})} )

这将创建无数的调查对和无数的答案,每一个都有其计数和无数的用户对该答案进行投票。

dotnetfiddle.net上尝试一下!

答案 2 :(得分:0)

看看以下内容是否有帮助:

   class Program
    {
        static void Main(string[] args)
        {
            List<Survey> surveys = new List<Survey>() {
                new Survey() { ID = 1, Survey_Id = "Apple_Survey", Answer = 1,  User = "Jones"},
                new Survey() { ID = 2, Survey_Id = "Apple_Survey", Answer = 1,  User = "Smith"},
                new Survey() { ID = 3, Survey_Id = "Banana_Survey", Answer = 2,  User = "Smith"},
                new Survey() { ID = 4, Survey_Id = "Apple_Survey", Answer = 3,  User = "Jane"},
                new Survey() { ID = 5, Survey_Id = "Banana_Survey", Answer = 2,  User = "John"}
            };

            var results = surveys.GroupBy(x => x.Survey_Id).Select(x => x.GroupBy(y => y.Answer)
                .Select(y => new { answer = y.Key, count = y.Count(), users = y.Select(z => z.User).ToList()}).ToList())
                .ToList();
        }

    }
    public class Survey
    {
        public int ID { get; set; }
        public string Survey_Id { get; set; }
        public int Answer { get; set; }
        public string User { get; set; }
    }