• 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:







  • 相关阅读:
    python开发环境安装
    python文件I/O
    python字符串方法以及注释
    python列表
    php: Can't use function return value in write context
    Notice : brew install php70
    对web开发从业者的发展方向的思考
    关于微信跨号支付
    MySQL触发器写法
    MySQL慢查询日志
  • 原文地址:https://www.cnblogs.com/chucklu/p/4597548.html
Copyright © 2020-2023  润新知