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:







  • 相关阅读:
    使用.sig签名验证文件
    ubuntu server 安装nextcloud12
    centos 搭建owncloud私有云
    archlinux错误:无法提交处理 (无效或已损坏的软件包)
    Oracle数据库-建库、建表空间,建用户
    JS中几种遍历方式
    常用的正则表达式
    JavaWeb中GET请求url传参中文乱码问题
    常用的ajax方式
    table中td内容过长自动换行
  • 原文地址:https://www.cnblogs.com/chucklu/p/4597548.html
Copyright © 2011-2022 走看看