code_junkie

Is there a cleaner syntax for applying an operation to each element of a sequence?

Nov 13th, 2011
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. int z = 1;
  2. double result = Math.Log(z); //works
  3.  
  4. int[] z = new [] {1,2,3,4};
  5. double[] result = Math.Log(z); //Syntax 1 - error CS1503: Argument '1': cannot convert from 'int[]' to 'double'
  6. double[] result = z.Select(p => Log(p)).ToArray(); //Syntax 2 - OK
  7.  
  8. static class LogExtension
  9. {
  10. public static IEnumerable<Double> Log(this IEnumerable<int> list)
  11. {
  12. foreach (int i in list)
  13. {
  14. yield return Math.Log(i);
  15. }
  16. }
  17. }
  18.  
  19. IEnumerable<Double> logValues = myInts.AsEnumerable().Log();
  20.  
  21. private static double[] getLogForIntArray(int[] z)
  22. {
  23. double[] q = (double[])z.Select(p => Math.Log(p)).ToArray();
  24. return q;
  25. }
  26.  
  27. double[] q = getLogForIntArray(z); // Syntax 3
  28.  
  29. int[] z = new [] {1,2,3,4};
  30. double[] result = Array.ConvertAll(z, p => Log(p));
  31.  
  32. double Log(int i) { return Math.Log(i); }
  33.  
  34. int[] z = new[] { 1, 2, 3, 4 };
  35. double[] result = Array.ConvertAll(z, Log);
  36.  
  37. double[] x = Array.ConvertAll(z, p => Math.Log(p));
  38.  
  39. int[] z = new [] {1,2,3,4};
  40. double[] result = z.Select(p => Log(p)).ToArray();
  41.  
  42. IEnumerable<int> z = new[] {1, 2, 3, 4};
  43. IEnumerable<double> result = z.Select(i => Math.Log(i));
  44.  
  45. var z = new[] {1, 2, 3, 4};
  46. var result = z.Select(i => Math.Log(i));
  47.  
  48. for (int i = 0; i < z.Length; i++)
  49. {
  50. Math.Log(z[i]);
  51. }
  52.  
  53. static void Process()
  54. {
  55. double[] test = { 1, 2, 3, 4 };
  56. double[] answer = new double[test.Length];
  57. for (int i = 0; i < test.Length; i++)
  58. {
  59. answer[i] = Math.Log(test[i]);
  60. }
  61.  
  62. }
Add Comment
Please, Sign In to add comment