code_junkie

Can this be refactored into nicey nice LINQ?

Nov 11th, 2011
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. IList<Breadcrumb> crumbs = new List<Breadcrumb>();
  2. bool foundCurrent = false;
  3. for (int a = 0; a < cachedCrumbs.Count; a++)
  4. {
  5. crumbs.Add(crumbs[a]);
  6. if (foundCurrent)
  7. {
  8. break;
  9. }
  10. foundCurrent = (crumbs[a + 1] != null && ((Breadcrumb)crumbs[a + 1]).IsCurrent);
  11. }
  12.  
  13. bool foundCurrent = false;
  14.  
  15. var crumbs = cachedCrumbs.TakeWhile(crumb => !foundCurrent)
  16. .Select(crumb => {
  17. foundCurrent = crumb == null || !crumb.IsCurrent;
  18. return crumb; });
  19.  
  20. var crumbs = cachedCrumbs.NewMethod(crumb => crumb == null || !crumb.IsCurrent);
  21.  
  22. IList<Breadcrumb> crumbs = new List<Breadcrumb>();
  23. for (int a = 0; a < cachedCrumbs.Count; a++)
  24. {
  25. crumbs.Add(cachedCrumbs[a]);
  26. if (cachedCrumbs[a] != null && cachedCrumbs[a].IsCurrent)
  27. {
  28. break;
  29. }
  30. }
  31.  
  32. IList<Breadcrumb> crumbs = new List<BreadCrumb>();
  33. foreach (Breadcrumb crumb in cachedCrumbs)
  34. {
  35. crumbs.Add(crumb);
  36. if (crumb != null && crumb.IsCurrent)
  37. {
  38. break;
  39. }
  40. }
  41.  
  42. // find the current item
  43. var currentItem = cachedCrumbs.First(c => c.IsCurrent);
  44. var currentIdx = cachedCrumbs.IndexOf(currentItem);
  45.  
  46. // get all items upto current item
  47. var crumbs = cachedCrumbs.Take(currentIdx + 2);
  48.  
  49. public static IEnumerable<T> TakeUpto<T>(this IList<T> theList, Func<T, bool> predicate)
  50. {
  51. var targetItem = theList.First(predicate);
  52. var targetIdx = theList.IndexOf(targetItem);
  53.  
  54. return theList.Take(targetIdx + 2);
  55. }
  56.  
  57. var crumbs = cachedCrumbs.TakeUpto(c => c.IsCurrent);
  58.  
  59. public static IEnumerable<T> TakeUpto<T>(this IEnumerable<T> theList, Func<T, bool> predicate)
  60. {
  61. foreach (T element in theList)
  62. {
  63. yield return element;
  64. if (predicate(element))
  65. {
  66. break;
  67. }
  68. }
  69. }
Add Comment
Please, Sign In to add comment