fork download
  1.  
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6.  
  7. public class EmployeeDto
  8. {
  9. public int Id { get; set; }
  10. public string Name { get; set; }
  11. }
  12.  
  13. public class EmployeeEntity
  14. {
  15. public int Id { get; set; }
  16. public string FullName { get; set; }
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23. List<object> o = new List<object>();
  24. o.Add(new EmployeeDto { Id = 1, Name = "Bob" });
  25. o.Add(null);
  26. o.Add(new EmployeeDto { Id = 2, Name = "Foo" });
  27. o.Add(null);
  28. o.AddRange(AddMilionOfEmployees());
  29.  
  30. Stopwatch sw = new Stopwatch();
  31. //sw.Start();
  32. //var employeeEntityList = MapList1(o);
  33. //sw.Stop();
  34. //Console.WriteLine("ElapsedTicks Solution 1 (OfType): " + sw.ElapsedTicks);
  35.  
  36. //Console.WriteLine("--");
  37.  
  38. //sw = new Stopwatch();
  39. sw.Start();
  40. var employeeEntityList2 = MapList2(o);
  41. sw.Stop();
  42. Console.WriteLine("ElapsedTicks Solution 2 (let): " + sw.ElapsedTicks);
  43.  
  44. Console.ReadKey();
  45. }
  46.  
  47. private static IEnumerable<object> AddMilionOfEmployees()
  48. {
  49. for (int i = 0; i < 100000; i++) //ideone doesn't allow a million.. ¬¬
  50. {
  51. Random randNum = new Random();
  52. yield return new EmployeeDto { Id = i, Name = String.Format("Employee{0}", i * randNum.Next()) };
  53. }
  54. }
  55.  
  56. private static IEnumerable<EmployeeEntity> MapList1(List<object> o)
  57. {
  58. return
  59. from i in o.OfType<EmployeeDto>()
  60. select new EmployeeEntity
  61. {
  62. Id = i.Id,
  63. FullName = i.Name
  64. };
  65. }
  66.  
  67. private static IEnumerable<EmployeeEntity> MapList2(List<object> o)
  68. {
  69. return
  70. from si in o
  71. let i = si as EmployeeDto
  72. where i != null
  73. select new EmployeeEntity
  74. {
  75. Id = i.Id,
  76. FullName = i.Name
  77. };
  78. }
  79.  
  80. }
Success #stdin #stdout 1.35s 54696KB
stdin
Standard input is empty
stdout
ElapsedTicks Solution 2 (let): 16115