簡體   English   中英

合並清單中的元素

[英]Combine elements of my List

我上了以下課:

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, ...

只需為折痕計算一個計數器,在碰到折痕時將其重置,遞增直到遇到非折痕,然后在執行當前操作之前將其輸出。 其他任何事情都是低效的,說實話,這是對問題的過度考慮。

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();
    } 
 }           
List<Action> actions = …

Console.WriteLine("{0} folds", actions.Sum(a => a.type == "folds" ? 1 : 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));

您可以使用如下的幫助器類:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM