简体   繁体   中英

Transform a table to add more columns in Linq in C#

I received very helpful advise in a previous post: Linq to group by 2 columns in C# - I'm trying to expand on that now, so that my ViewModel looks the way it should for the view:

My first query:

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);

Returns:

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

I want to take that table, and transform it to:

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

I was trying the query below, but am getting myself mixed up - all of the Teams show just 1 or 0 in each if the Open/Closed columns:

        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(),

          });

I am also trying in LinqPad, but having difficulty getting it to work inthere too.

Thanks for your help,

Mark

What you have here won't even compile, because you're defining qbt2 on the left-hand side, and using it on the right-hand side. Now, assuming that you meant qbt on the right-hand side, that's a rather inefficient implementation to GroupBy , and then walk the whole sequence looking for matching keys. The GroupBy already gives you the sequence elements that you need, so use it. And then, barring both of those mistakes, you're counting the number of rows that match a given Team, Status pair, rather than summing the Number value for a given pair. Thus:

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)
       });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM