Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: C#  |  size: 1.57 KB  |  hits: 37  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Collections;
  6.  
  7. namespace osisp_ex_enums
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             IEnumerable<string> source = new string[] { "one", "two", "three", "four" };
  14.             Func<string, bool> predicateFunc = Predicate;
  15.  
  16.             IEnumerable<string> stringEnum = StringListEnumerator.Where(source, predicateFunc);
  17.  
  18.             foreach (string stringOutput in stringEnum)
  19.             {
  20.                 Console.WriteLine(stringOutput);
  21.             }
  22.  
  23.             Console.ReadLine();
  24.         }
  25.  
  26.         private static bool Predicate(string input)
  27.         {
  28.             if (input.Length > 3)
  29.                 return true;
  30.  
  31.             return false;
  32.         }
  33.     }
  34.  
  35.     public static class StringListEnumerator
  36.     {
  37.         public static IEnumerable<string> Where(this IEnumerable<string> source, Func<string, bool> predicate)
  38.         {
  39.             //with enumerator
  40.  
  41.             IEnumerator<string> stringEnum = source.GetEnumerator();
  42.  
  43.             while (stringEnum.MoveNext())
  44.             {
  45.                 if (predicate(stringEnum.Current))
  46.                 {
  47.                     yield return stringEnum.Current;
  48.                 }
  49.             }
  50.  
  51.             //or without it
  52.  
  53.             /*foreach (string inputString in source)
  54.             {
  55.                 if (predicate(inputString))
  56.                 {
  57.                     yield return inputString;
  58.                 }
  59.             }*/
  60.         }
  61.     }
  62. }