fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5.  
  6. public class MyClass
  7. {
  8. public int Id { get; private set; }
  9. public string Name { get; private set; }
  10.  
  11. public MyClass(int id)
  12. {
  13. this.Id = id;
  14. this.Name = id.ToString();
  15. }
  16. }
  17.  
  18. class Program
  19. {
  20. static void Main(string[] args)
  21. {
  22. var rand = new Random();
  23. var arrayA = Enumerable.Range(1, 10000).Select(_ => new MyClass(rand.Next(1, 100))).ToArray();
  24. var arrayB = Enumerable.Range(1, 10000).Select(_ => new MyClass(rand.Next(1, 100))).ToArray();
  25.  
  26. GC.Collect();
  27. GC.WaitForPendingFinalizers();
  28. GC.Collect();
  29. var sw = Stopwatch.StartNew();
  30.  
  31. var ret = (
  32. from a in arrayA
  33. join b in arrayB on a.Id equals b.Id
  34. select a.Name).ToList();
  35.  
  36. sw.Stop();
  37. Console.WriteLine(sw.Elapsed);
  38.  
  39. GC.Collect();
  40. GC.WaitForPendingFinalizers();
  41. GC.Collect();
  42. sw.Reset(); sw.Start();
  43.  
  44. var ret2 = new List<string>();
  45. var lookup = arrayB.ToLookup(x => x.Id);
  46. foreach (var itemA in arrayA)
  47. {
  48. foreach (var itemB in lookup[itemA.Id])
  49. {
  50. ret2.Add(itemA.Name);
  51. }
  52. }
  53.  
  54. sw.Stop();
  55. Console.WriteLine(sw.Elapsed);
  56.  
  57. Console.Write("check result : ");
  58. Console.WriteLine(ret.SequenceEqual(ret2));
  59. }
  60. }
stdin
Standard input is empty
compilation info
prog.cs(48,26): warning CS0168: The variable `itemB' is declared but never used
Compilation succeeded - 1 warning(s)
stdout
00:00:00.1688902
00:00:00.0924882
check result : True