2014-10-07 210 views
0

我已经声明数据表由一组这样的:C#循环通过关键

var finalResult = (from r in result.AsEnumerable() 
           group r by new 
           { 
            r.Agent, 
            r.Reason 
           } into grp 
           select new 
           { 
            Agent = grp.Key.Agent, 
            Reason = grp.Key.Reason, 
            Count = grp.Count() 
           }).ToList(); 

finalResult将是这样的:

agent1 reason1 4 
agent1 reason2 7 
agent2 reason1 8 
agent2 reason2 3 
.. 
... 
... 
agentn reason1 3 
agentn reason2 11 

我要循环代理名称为了得到每个代理人的每个理由的原因和计数。 换句话说:我需要建立这样的:

enter image description here

你能告诉我请如何循环代理名称从finalResult变量?

回答

2

你需要一个更的GroupBy和你做:

var solution = 
     finalResult 
     .GroupBy(x => x.Agent); 
foreach (var group in solution) 
     { 
      // group.Key is the agent 
      // All items in group are a sequence of reasons and counts for this agent 
      foreach (var item in group) 
      { 
       // Item has <Agent, Reason, Count> and belongs to the agent from group.Key 
      } 
     } 

外环越过所有代理(如代理1,代理2等),而内部循环将通过所有原因代理当前代理。

0

你可能想尝试的GroupBy在LINQ:

你可以阅读更多关于它here

0

也许:

var agentGroups = finalResult 
    .GroupBy(x => x.Agent) 
    .Select(ag => new 
    { 
     Agent = ag.Key, 
     ReasonCounts = ag.GroupBy(x => x.Reason) 
         .Select(g => new 
         { 
          Agent = ag.Key, 
          Reason = g.Key, 
          Count = g.Sum(x => x.Count) 
         }).ToList(), 
     Total_Count = ag.Sum(x => x.Count) 
    }); 
foreach (var agentGroup in agentGroups) 
{ 
    string agent = agentGroup.Agent; 
    int totalCount = agentGroup.Total_Count; 
    foreach (var reasonCount in agentGroup.ReasonCounts) 
    { 
     string reason = reasonCount.Reason; 
     int count = reasonCount.Count; 
    } 
}