tags:

views:

82

answers:

4

Hi,

I got following class:

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

Which is used in a List:

public List<Action> Action

Depending on type I display some custom text. But if type = "folds" I just display 1 Folds. If there are many folds after another, it currently displays:

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

How can I combine those folds in a smart way and display it like this:

3 folds, ...
A: 
List<Action> actions = …

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

Just make a counter for the folds, reset it when you hit a fold, increment until you hit a non-fold, then output it before doing the current action. Anything else is inefficient and, honestly, overthinking the issue.

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();
    } 
 }
Faqa
A: 

You can use linq to group the elements by type, then process these groups to get the desired output:

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));
Lee
I wondered that as well, but you need to get the count of *consecutive* equal actions.
Jon Skeet
A: 

You could use helper class like this:

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;
  }
}
Alex Ustinov