合并我的列表元素

时间:2009-11-15 19:18:22

标签: c# list

我上课了:

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

List中使用的内容:

public List<Action> Action

根据type我会显示一些自定义文字。但如果type = "folds"我只显示1 Folds。如果有多个folds接一个,则会显示:

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

如何以智能方式组合这些folds并将其显示如下:

3 folds, ...

4 个答案:

答案 0 :(得分: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();
    } 
 }           

答案 1 :(得分:0)

List<Action> actions = …

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

答案 2 :(得分: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));

答案 3 :(得分: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;
  }
}