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:







  • 相关阅读:
    容器与线程--更新
    js生成元素的事件不执行问题
    Webpack 笔记
    思考题——爬楼梯
    正则表达式笔记
    github + travis 自动构建 vue 项目到 gitpage
    css3 动画 vs js 动画
    深度哲学对工作的启发
    yml 文件操作方法
    布尔变量在项目中的应用
  • 原文地址:https://www.cnblogs.com/chucklu/p/4597548.html
Copyright © 2011-2022 走看看