Since you're using C#, you can make your initializers a bit nicer: Grid g = new Grid() { g.Width = 50, g.Height = 50, g.Tag = focus, } //Canvas.SetZIndex(g, 100); The last part of your code (or rather, the second half) does very similar things multiple times: code duplication is a sign your code can be made clearer. For instance (note that your code almost surely contains a bug! The statement inside all the loops invokes s2 and not s3): foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { foreach (SourceFile s3 in s2.getInvocations()) { invoCount = invoCount + s2.getInvocations().Count; } } } } } can be changed into list.CountRecursive(t => t.getInvocations(), t => t.getInvocations().Count, 5); (...) public static int CountRecursive<T>(this IEnumerable<T> x, Func<T, IEnumerable<T>> f, Func<T, int> c, int depth) { int counter = 0; foreach (T t in x) { if (depth > 1) { counter += f(t).CountRecursive(f, c, depth - 1); } else { counter += c(t); } } return counter; } which also makes it a lot easier to do it for different recursion levels.