Share via


Introducing Lambda Expressions – Validating a List without a loop

    1: using System;
    2: using System.Collections.Generic;
    3: using System.Linq;
    4:  
    5: namespace LambdaExpressionDemo
    6: {
    7:     interface IValidator
    8:     {
    9:         bool Validate();
   10:     }
   11:  
   12:     class RandomValidator : IValidator
   13:     {
   14:         private static Random randomGenerator = new Random();
   15:  
   16:         int value = 0;
   17:  
   18:         public RandomValidator()
   19:         {
   20:             value = randomGenerator.Next() % 2;
   21:         }
   22:  
   23:         public bool Validate()
   24:         {
   25:             return value == 0;
   26:         }
   27:     }
   28:  
   29:     class Program
   30:     {
   31:         static void Main(string[] args)
   32:         {
   33:             bool success = false;
   34:             while (!success)
   35:             {
   36:                 //We have a list of items for example controls
   37:                 List<IValidator> listOfItemsToValidate = new List<IValidator>();
   38:                 for (int count = 0; count < 5; count++)
   39:                     listOfItemsToValidate.Add(new RandomValidator());
   40:  
   41:                 //We want to validate that the value of all the items 
   42:                 //even number.
   43:  
   44:                 //Without Lambda Expressions we would have validated the 
   45:                 //list using a for loop
   46:                 success = true;
   47:                 foreach (IValidator item in listOfItemsToValidate)
   48:                     success &= item.Validate();
   49:  
   50:                 //With Lambda Expressions we could do the 
   51:                 //validation in a single statement
   52:                 bool success2 = listOfItemsToValidate.Where(
   53:                     (item) => !item.Validate()).Count() == 0;
   54:             }
   55:         }
   56:     }
   57: }

Comments

  • Anonymous
    December 20, 2009
    That's great. But is there a difference in performance?

  • Anonymous
    December 29, 2009
    Hello, Using the "Where" will not have a difference in performance against the foreach both approaches will have O(n) in best and worst cases. However the lambda expression can be substituted with this one: bool success3 = !listOfItemsToValidate.Any((item) => !item.Validate()); This new expression will have a O(n) in worst case scenario but a O(1) in best case which is better that the statement above. Thanks, Youhana