【问题标题】:How to use Linq instead of foreach to Group and Count如何使用 Linq 而不是 foreach 进行分组和计数
【发布时间】:2014-01-16 14:25:39
【问题描述】:

我有 2 个列表,一个用于球员,另一个用于教练。

为了计算属于教练的玩家数量,我使用了:

  var g = AllePlayer.GroupBy(play=> play.coachNumer);
  foreach (var grp in g)
  {
      foreach (Coach co in AlleCoaches)
      {
          if (co.coachNumer== grp.Key)
          {
              co.NumOfPlayer= grp.Count();
          }
       }
  }

现在我想知道是否有一种很好的方法可以将带有“foreach”的情人部分放在一个很好的 Linq 语法中,以避免这种“foreach”循环。 提前谢谢!

【问题讨论】:

    标签: c# linq foreach


    【解决方案1】:

    你可以稍微改变一下这个说法。由于最终您想更改每个教练的属性,因此最简单的方法是遍历该列表,如下所示:

    foreach (Coach co in AlleCoaches)
    {
        co.NumOfPlayer= AllePlayer.Where(p => p.coachNumber == co.coachNumber)
                                  .Count();
    }
    

    【讨论】:

    • 简单多了!
    【解决方案2】:
    AlleCoaches.ToList()
    .ForEach(n=>n.NumOfPlayer=AllePlayer.Where(n=>coachNumer==n.coachNumer).Count());
    

    【讨论】:

    • 非常快速和肮脏:)
    • is AlleCoaches 是一个列表,您不需要将其设为 ToList()。
    【解决方案3】:

    这将是一种更简单的方法:

    var query = AllePlayer.GroupBy(player => player.coachNumer,
                                   (coach, players => new {
                                       Coach = coach,
                                       Count = players.Count() }));
    

    这将为您提供一个序列,其中每个元素是教练和该教练的球员人数。

    然后你可以遍历结果,并将值赋给Coach.NumOfPlayer,但你真的需要吗?如果你这样做,它会这样做:

    foreach (var pair in query)
    {
        pair.Coach.NumOfPlayer = pair.Count;
    }
    

    个人感觉“玩家数量”不应该是Coach类型的一部分...

    【讨论】:

      【解决方案4】:
      var g = AllePlayer.TakeWhile(play=> ( play.coachNumer!=null));
      

      你可以采用任何你需要的逻辑,但语法是一样的。

      var count = g.Count();
      

      【讨论】:

        猜你喜欢
        • 2016-08-08
        • 2014-10-23
        • 1970-01-01
        • 1970-01-01
        • 2010-12-08
        • 2010-09-27
        • 2013-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多