Linq之Sum用法新體會


  1、簡單應用,求數組的和,示例:

    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    double numSum = numbers.Sum();
 
    Console.WriteLine("The sum of the numbers is {0}.", numSum);

  那么,求其中除以2等於0元素。按我平時的思路,就會這樣寫:

   int[] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0};

   double numSum = numbers.Where(x=>x%2==0).Count();

  其實,可以這樣寫的;

 

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

  Enumerab類的擴張方法

  Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate),

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM