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







  • 相关阅读:
    P24—动态数组没有{}
    JavaB站学习————接口在开发中的作用
    JavaB站学习————extends和implements同时出现
    JavaB站学习————一个类可以实现多个接口以及接口的总结
    JavaB站学习————接口和多态联合使用。
    01日语五十音
    07 递归&&命名风格&&作业(结构体,malloc,函数,递归)
    JavaB站学习——作业16
    电子书
    破解压缩包
  • 原文地址:https://www.cnblogs.com/chucklu/p/4597548.html
Copyright © 2020-2023  润新知