Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press

Buy directly from Paradoxal Press at $33.99 (Save 43%)



Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA


Listing 15-22 extracted from chapter Collections


Listing 15-21<     > Listing 15-23


This listing can be compiled with the command line:
csc.exe /target:exe Example_15_22.cs
Errors: 0 Warnings: 0


Example_15_22.cs
using System.Collections.Generic;
class Program {
   class Article {
      public Article(decimal price,string name){Price=price;Name=name;}
      public readonly decimal Price;
      public readonly string  Name;
   }

   static bool IsEven(int i) { return i % 2 == 0; }
   static int sum = 0;
   static void AddToSum(int i) { sum += i; }
   static int CompareArticle(Article x, Article y){
      return Comparer<decimal>.Default.Compare(x.Price, y.Price);
   }
   static decimal ConvertArticle(Article article){
      return (decimal)article.Price;
   }

   static void Main(){
      // Seek out every odd integers. 
      // Implicitly uses a 'Predicate<T>' delegate object.
      List<int> integers = new List<int>();
      for(int i=1; i<=10; i++) 
         integers.Add(i);
      List<int> even = integers.FindAll( IsEven );

      // Sum up items of the list.
      // Implicitly uses an 'Action<T>' delegate object.
      integers.ForEach( AddToSum );

      // Sort items of type 'Article'.
      // Implicitly uses a 'Comparison<T>' delegate object.
      List<Article> articles = new List<Article>();
      articles.Add( new Article(5,"Shoes") );
      articles.Add( new Article(3,"Shirt") );
      articles.Sort( CompareArticle );

      // Cast items of type 'Article' into 'decimal'.
      // Implicitly uses a 'Converter<T,U>' delegate object.
      List<decimal> artPrice = 
                articles.ConvertAll<decimal>( ConvertArticle );
   }
}	
Copyright Patrick Smacchia 2006 2007