code_junkie

Fastest way to find objects from a collection matched by condition on string member

Nov 11th, 2011
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. class ClassFoo
  2. {
  3. public string word;
  4. public float score;
  5. //... etc ...
  6. }
  7.  
  8. List<ClassFoo> result = new List<ClassFoo>();
  9. foreach (ClassFoo cf in collection)
  10. {
  11. if (cf.word.StartsWith(query) || cf.word.EndsWith(query))
  12. result.Add(cf);
  13. }
  14.  
  15. Dictionary<char, List<ClassFoo>> indexByFirstLetter;
  16. foreach (var cf in collection) {
  17. indexByFirstLetter[cf.bar[0]] = indexByFirstLetter[cf.bar[0]] ?? new List<ClassFoo>();
  18. indexByFirstLetter[cf.bar[0]].Add(cf);
  19. indexByFirstLetter[cf.bar[cf.bar.length - 1]] = indexByFirstLetter[cf.bar[cf.bar.Length - 1]] ?? new List<ClassFoo>();
  20. indexByFirstLetter[cf.bar[cf.bar.Length - 1]].Add(cf);
  21. }
  22.  
  23. foreach (ClasssFoo cf in indexByFirstLetter[query[0]]) {
  24. if (cf.bar.StartsWith(query) || cf.bar.EndsWith(query))
  25. result.Add(cf);
  26. }
Add Comment
Please, Sign In to add comment