Actions, Predicates and Funcs


/ Published in: C#
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.