code_junkie

Fastest way to find common items across multiple lists in C#

Nov 10th, 2011
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. List<List<Option>> optionLists;
  2.  
  3. var x = from list in optionLists
  4. from option in list
  5. where optionLists.All(l => l.Any(o => o.Value == option.Value))
  6. orderby option.Value
  7. select option;
  8.  
  9. static SortedDictionary<T,bool>.KeyCollection FindCommon<T> (List<List<T>> items)
  10. {
  11. SortedDictionary<T, bool>
  12. current_common = new SortedDictionary<T, bool> (),
  13. common = new SortedDictionary<T, bool> ();
  14.  
  15. foreach (List<T> list in items)
  16. {
  17. if (current_common.Count == 0)
  18. {
  19. foreach (T item in list)
  20. {
  21. common [item] = true;
  22. }
  23. }
  24. else
  25. {
  26. foreach (T item in list)
  27. {
  28. if (current_common.ContainsKey (item))
  29. {
  30. common [item] = true;
  31. }
  32. }
  33. }
  34.  
  35. if (common.Count == 0)
  36. {
  37. current_common.Clear ();
  38. break;
  39. }
  40.  
  41. SortedDictionary<T, bool>
  42. swap = current_common;
  43.  
  44. current_common = common;
  45. common = swap;
  46. common.Clear ();
  47. }
  48.  
  49. return current_common.Keys;
  50. }
  51.  
  52. static void Main (string [] args)
  53. {
  54. Random
  55. random = new Random();
  56.  
  57. List<List<int>>
  58. items = new List<List<int>>();
  59.  
  60. for (int i = 0 ; i < 10 ; ++i)
  61. {
  62. List<int>
  63. list = new List<int> ();
  64.  
  65. items.Add (list);
  66.  
  67. for (int j = 0 ; j < 100 ; ++j)
  68. {
  69. list.Add (random.Next (70));
  70. }
  71. }
  72.  
  73. SortedDictionary<int, bool>.KeyCollection
  74. common = FindCommon (items);
  75.  
  76. foreach (List<int> list in items)
  77. {
  78. list.Sort ();
  79. }
  80.  
  81. for (int i = 0 ; i < 100 ; ++i)
  82. {
  83. for (int j = 0 ; j < 10 ; ++j)
  84. {
  85. System.Diagnostics.Trace.Write (String.Format ("{0,-4:D} ", items [j] [i]));
  86. }
  87.  
  88. System.Diagnostics.Trace.WriteLine ("");
  89. }
  90.  
  91. foreach (int item in common)
  92. {
  93. System.Diagnostics.Trace.WriteLine (String.Format ("{0,-4:D} ", item));
  94. }
  95. }
  96.  
  97. var sharedOptions =
  98. from option in optionLists.First( ).Distinct( )
  99. where optionLists.Skip( 1 ).All( l => l.Contains( option ) )
  100. select option;
Add Comment
Please, Sign In to add comment