Trying to pivot data using linq [duplicate]

雨燕双飞 提交于 2019-12-03 08:55:30

If I understand the question, you want a mapping of Task to State for each Robot. You could group by Robot and select a dictionary for each group:

Logs.GroupBy(t => t.Robot).Select(g => new {
    Robot = g.Key,
    TaskStates = g.ToDictionary(t => t.Task, t => t.State)
})

This assumes that task names are unique for each robot (ToDictionary would throw an exception otherwise).

You could also add another level of grouping for dates:

Logs.GroupBy(t => t.LogDate).Select(g => new {
    Date = g.Key,
    Details = g.GroupBy(t => t.Robot).Select(g => new {
        Robot = g.Key,
        TaskStates = g.ToDictionary(t => t.Task, t => t.State)
    }).ToList()
})

Note that the Details property is essentially equivalent to my first example, the only difference being that it queries the outer grouping instead of the whole sequence. The result is a sequence of {Date, Details} where each "detail" is a list of {Robot, TaskStates}.

I haven't tested this, so let me know if there are any bugs I missed.

var result = Logs.GroupBy(x=> new {x.Robot, x.Date})                     
                 .Select(g=> {
                               var a = g.ToList();
                               return
                               new {
                                 a[0].Robot,
                                 a[0].Date,
                                 Task1 = a[0].State,
                                 Task2 = a[1].State,
                                 Task4 = a[2].State
                               };
                             });

Suppose you have to define a fixed number of Tasks and to make it safer, we can do something like this:

var result = Logs.GroupBy(x=> new {x.Robot, x.Date})
                 .Select(g=> { 
                               var c = g.Count();
                               var a = g.ToList();
                               return 
                               new {
                                    a[0].Robot,
                                    a[0].Date,
                                    Task1 = a[0].State,
                                    Task2 = c > 1 ? a[1].State : "",
                                    Task4 = c > 2 ? a[2].State : ""
                                   };
                             });

try this:

var newData = from w in Logs
              where w.LogDate >= start && w.LogDate <= finish
              group w by w.LogDate into g
              select new 
              {
                  LogDate = g.Key,
                  Details = g.ToList().OrderBy(o => o.Robot)
              };

The query newData contains a list of objects with LogDate and Detais (List of tasks ordered by Robot).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!