2014-10-07 408 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; 
    } 
}