转换表以在C#中的Linq中添加更多列

时间:2013-05-28 13:27:35

标签: c# linq linq-to-sql

我在上一篇文章中收到了非常有用的建议:Linq to group by 2 columns in C# - 我正在尝试对此进行扩展,以便我的ViewModel看起来应该是视图的方式:

我的第一个问题:

var qbt = db.Calls.GroupBy(calls => new { calls.assignedteam, calls.status })
            .Select(call => new StatusByTeamViewModel1
        {
            Team = call.Key.assignedteam,
            Status = call.Key.status,
            Number = call.Count()
        }).OrderBy(z => z.Team).ThenBy(z => z.Status);

返回:

Team  Number Status
ta    40     Open
ta    60     Closed
tb    58     Open
tb    40     Closed
tc    1      Open
tc    122    Closed

我想把那个表转换成:

Team Open Closed
ta   40   60
tb   58   40
tc   1    122

我正在尝试下面的查询,但是让自己混淆了 - 如果打开/关闭列,所有团队每个只显示1或0:

        var qbt2 = qbt.GroupBy(x => x.Team)
          .Select(call => new StatusByTeamAllViewModel2
          {
              Team = call.Key,
              Open = qbt2.Where(it => it.Status == "Open" && it.Team==call.Key).Count(),
              Closed = qbt2.Where(it => it.Status == "Closed" && it.Team == call.Key).Count(),

          });

我也在尝试使用LinqPad,但很难让它在内部工作。

感谢您的帮助,

标记

1 个答案:

答案 0 :(得分:4)

你在这里所拥有的东西甚至都不会编译,因为你在左侧定义qbt2,在右侧使用它。现在,假设您在右侧表示qbt,这对GroupBy来说是一个相当低效的实现,然后遍历整个序列以查找匹配的键。 GroupBy已经为您提供了所需的序列元素,因此请使用它。然后,除了这两个错误之外,您还要计算与给定Team, Status对匹配的行数,而不是将给定对的Number值相加。因此:

var qbt2 = 
    qbt.GroupBy(x => x.Team)
       .Select(g => new StatusByTeamAllViewModel2 {
           Team = g.Key,
           Open = g.Where(x => x.Status == "Open").Sum(x => x.Number)
           Closed = g.Where(x => x.Status == "Closed").Sum(x => x.Number)
       });