zoukankan      html  css  js  c++  java
  • Counting sheep...

    Counting sheep...

    Description:

    Consider an array of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).

    For example,

    [true,  true,  true,  false,
      true,  true,  true,  true ,
      true,  false, true,  false,
      true,  false, false, true ,
      true,  true,  true,  true ,
      false, false, true,  true]

    using System;
    
    public static class Kata
    {
      public static int CountSheeps(bool[] sheeps)
      {
        int count = 0;
        for(int i = 0; i < sheeps.Length; i++) {
          if (sheeps[i]) count++;
        }
        return count;
      }
    }


    比较好的方法,是使用Linq
    using System;
    using System.Linq;
    
    public static class Kata
    {
      public static int CountSheeps(bool[] sheeps)
      {
        return sheeps.Count(s => s);
      }
    }

    Array类的扩展方法Count

    public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

     


    http://www.codeproject.com/Articles/383749/How-does-it-work-in-Csharp-Part-Csharp-LINQ-in-d

    In .NET any data structure which is derived from the IEnumerable<T> interface of the System.Collections.Generic namespace of the mscorlib.dll (this assembly is located in C:WindowsMicrosoft.NETFrameworkv4.0.30319 but depends on the installation of the VS) assembly is able to access all the extension methods defined in the Enumerable class of the System.Linq namespace of the System.Core.dll assembly in the .NET Framework (see more about LINQ). This Enumerable class is a static non inheritable class defined in the System.Linq namespace of the System.Core.dll assembly(C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Corev4.0_4.0.0.0__b77a5c561934e089System.Core.dll but depends on the installation of VS). The definition of the Enumerbale class is as below:







  • 相关阅读:
    MySQL—2、B-Tree,B+Tree,聚集索引,非聚集索引
    transient关键字的作用及使用方法
    通过Executors创建线程池和注意小点
    @Validated校验
    Elasticsearch-head插件的安装与配置
    bayaim_java_入门到精通_听课笔记bayaim_20181120
    bayaim_hadoop2_hdfs_20181107
    bayaim_hadoop1_2.2.0伪分布式搭建
    bayaim_hadoop 开篇 0.0
    bayaim_linux_configure_oracle
  • 原文地址:https://www.cnblogs.com/chucklu/p/4597548.html
Copyright © 2011-2022 走看看