2009-11-15 36 views
0

我得到了下面的類:聯合元素

public class Action 
{ 
    public Player player { get; private set; } 
    public string type { get; private set; } 
    public decimal amount { get; private set; } 
} 

這是在列表中使用:

public List<Action> Action 

根據type我顯示一些自定義文本。但是,如果type = "folds"我只顯示1 Folds。如果有很多folds層出不窮,但目前顯示:

1 folds, 1 folds, 1 folds, ... 

我如何可以結合使用這些folds在一個巧妙的方法和這樣顯示出來:

3 folds, ... 

回答

1

只是做一個計數器摺疊時,重置它,當你點擊一個摺疊,增加,直到你沒有摺疊,然後在執行當前動作之前輸出它。其他任何東西都是低效率的,並且誠實地說是超越了這個問題。

int counter = 0; 
foreach Action currAction in Action 
{ 
    if (currAction.Type == "fold") 
    { 
     ++counter; 
    } 
    else 
    { 
     if (counter > 0) 
     { 
      \\ print it out and reset to zero 
     } 
     DoStuff(); 
    } 
}   
0
List<Action> actions = … 

Console.WriteLine("{0} folds", actions.Sum(a => a.type == "folds" ? 1 : 0)); 
0

您可以通過類型使用LINQ組的元素,然後處理這些組以獲得所需的輸出:

var actionGroups = actions.GroupBy(a => a.type); 
IEnumerable<string> formattedActions = actionGroups 
    .Select(grp => new[] { Type = grp.Key, Count = grp.Count}) 
    .Select(g => String.Format("{0} {1}{2}", g.Count, g.Type, g.Count == 1 ? "s" : String.Empty)); 
+0

我也想知道這一點,但你需要計算*連續*相等的動作。 –

0

你可以使用輔助類是這樣的:

public class ActionMessages : IEnumerable<string> 
{ 
    private IEnumerable<Action> actions; 

    public IEnumerator<string> GetEnumerator() 
    { 
    int foldCount = 0;  
    foreach(var action in this.actions) { 
     if (action.type=='fold') 
     foldCount++; 
     else { 
     if (foldCount>0) 
      yield return foldCount.ToString() + " folds"; 
     foldCount = 0; 
     yield return action.ToString(); 
     } 
    } 
    if (foldCount>0) 
     yield return foldCount.ToString() + " folds"; 
    } 

    // Constructors 

    public ActionMessages (IEnumerable<Action> actions) 
    { 
    this.actions = actions; 
    } 
}