GetElementListsOrderedByDepth(IEnumerable <XElement> nodes) { var cmp = Make.Comparer <int>((v1, v2) => v2 - v1); var sortedDict = new SortedDictionary <int, List <XElement> >(cmp); foreach (var element in nodes) { var depth = element.Depth(); var list = sortedDict.GetValueOrDefault(depth); if (list == null) { list = new List <XElement>(); sortedDict.Add(depth, list); } list.Add(element); } return(sortedDict); }