Posted By

azmi on 10/23/13


Tagged

action func predicate


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

CSB_Campaigner


Actions, Predicates and Funcs


 / Published in: C#
 

Short sample code on how to create and use Actions, Predicates and Funcs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ActionPredicateFuncExample
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. List<string> list = new List<string> { "Coding", "in", "C#", "Rules!" };
  14.  
  15. Action<string> tmp = (f) => Console.WriteLine(f);
  16. var print = new Action<string>(tmp);
  17.  
  18. foreach (var item in list)
  19. print(item);
  20.  
  21. Predicate<string> pred = new Predicate<string>(CStringSearch);
  22. List<string> list2 = list.FindAll(pred);
  23. foreach (var item in list2)
  24. Console.WriteLine(item);
  25.  
  26. Func<string, bool> isContainsN = f => f.Contains("n");
  27. foreach (var item in list)
  28. {
  29. if (isContainsN(item)) Console.WriteLine(item);
  30. }
  31.  
  32. Console.ReadLine();
  33. }
  34.  
  35. private static bool CStringSearch(string s)
  36. {
  37. return (s.Contains("C"));
  38. }
  39. }
  40. }

Report this snippet  

You need to login to post a comment.