Guest User

Untitled

a guest
Jun 24th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. List<int> numbers = new List<int> { 1, 5, 6, 3, 8, 7, 9, 2, 3, 4, 5, 6, };
  2.  
  3. // To get the count of those that are less than four we might write:
  4. int lessThanFourCount = numbers.Where(n => n < 4).Count();
  5.  
  6. // But this can also be written as:
  7. Func<int, bool> lessThanFour = n => n < 4;
  8.  
  9. int lessThanFourCount = numbers.Where(lessThanFour).Count();
  10.  
  11. ...
  12. DoSomethingPotentiallyBad((x) => x * 2, 0); // both delegates do
  13. DoSomethingPotentiallyBad((x) => 2 / x, 0); // something different ...
  14. ...
  15.  
  16. static int DoSomethingPotentiallyBad(Func<int, int> function, int input)
  17. {
  18. // ... but get exception handled all the same way
  19. try
  20. {
  21. return function.Invoke(input);
  22. }
  23. catch
  24. {
  25. Console.WriteLine("Evaluation failed! Return 0.");
  26. return 0;
  27. }
  28. }
  29.  
  30. public static string ToDelimitedString<T>(
  31. this IEnumerable<T> source, Func<T, string> converter, string separator)
  32. {
  33. // error checking removed for readability
  34.  
  35. StringBuilder sb = new StringBuilder();
  36. foreach (T item in source)
  37. {
  38. sb.Append(converter(item));
  39. sb.Append(separator);
  40. }
  41.  
  42. return (sb.Length > 0) ?
  43. sb.ToString(0, sb.Length - separator.Length) : string.Empty;
  44. }
  45.  
  46. // ...
  47.  
  48. List<int> e1 = new List<int> { 1, 2, 3 };
  49. // convert to "2|4|6"
  50. string s1 = e1.ToDelimitedString(x => (x * 2).ToString(), "|");
  51.  
  52. DateTime[] e2 = new DateTime[]
  53. { DateTime.Now.AddDays(-100), DateTime.Now, DateTime.Now.AddDays(100) };
  54. // convert to "Tuesday, Thursday, Saturday"
  55. string s2 = e2.ToDelimitedString(x => x.DayOfWeek.ToString(), ", ");
  56.  
  57. List<MyCustomType> e3 = new List<MyCustomType>
  58. { new MyCustomType("x"), new MyCustomType("y"), new MyCustomType("z") };
  59. // convert to "X and Y and Z"
  60. string s3 = e3.ToDelimitedString(x => x.Name.ToUpper(), " and ");
Add Comment
Please, Sign In to add comment