2009-11-15 35 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; 
    } 
}