加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 需要更好的方法来总结数据

发布时间:2020-12-15 03:59:41 所属栏目:百科 来源:网络整理
导读:我有这个班 public class ConnectionResult{ private int connectionPercentage; public int ConnectPercentage { get { return connectionPercentage; } } public ConnectionResult(int ip) { // Check connection and set connectionPercentage }} 并且我
我有这个班
public class ConnectionResult
{
  private int connectionPercentage;

  public int ConnectPercentage
  {
     get { return connectionPercentage; }
  }

  public ConnectionResult(int ip)
  {
     // Check connection and set connectionPercentage
  }
}

并且我有一个经理可以获得ConnectionResult的几个列表,并对每个值进行计数,然后再按配置确定的特定数字.我的实现是这样的:

public class CurrentConnections
{
  private static CurrentConnections inst;

  private CurrentConnections()
  {

  }

  public static CurrentConnections GetInstance
  {
     get
     {
        if (inst != null)
        {
           inst = new CurrentConnections();
        }
        return inst;
     }
  }

   public int CountActiveConnections(params List<ConnectionResult>[] conns)
   {
     int rtVal = 0;

     foreach (List<ConnectionResult> connectionResult in conns)
     {
        foreach (var currConn in connectionResult)
        {
           if (currConn.ConnectPercentage > ACCEPTABLE_CONNECTION)
           {
              rtVal++;
           }
        }
     }

     return rtVal;
  }
}

但是我想让它更好,所以我开始写在linq,我得到了

conns.Count(x => x.Count(y => y.ConnectPercentage > ACCEPTABLE_CONNECTION));

但是这给我一个错误,不能将类型’int’隐式转换为’bool’.
有没有办法计算在linq或我必须留下我写的?
btw,我是linq的新手

解决方法

John Skeet‘s answer是非常好的,但为了解决你看到的错误,查询将是:
conns.Sum(x => x.Count(y => y.ConnectPercentage > ACCEPTABLE_CONNECTION));

> Count接受一个返回bool的函数,并返回满足该条件的集合中的项目数.
> Sum接受一个函数返回int(等等),并返回应用于每个项目的表达式的结果的总和.

当然,无论您选择每个子集中的每个项目,然后对其进行计数(如John Skeet建议),还是计算每个子集中的项目,然后将其计数(如我的代码所示),结果将完全相同相同.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读