public IReadOnlyList <Pair <ILNode, IndexRange> > FindRelatedNodesCore(IndexRange targetRange, int maxSearchResults, bool trim) { var candidates = new Dictionary <Pair <ILNode, IndexRange>, float>(); // This is a heuristic search, not an algorithm; it is not guaranteed to find the // best answer, rather we scan enough entries to find what we're looking for with // high probability. In total, scan about 10x as many entries as maxSearchResults. Scan(_startLocations, targetRange.StartIndex, targetRange, 1, maxSearchResults * 5, candidates); Scan(_startLocations, targetRange.StartIndex, targetRange, -1, maxSearchResults * 2, candidates); Scan(_endLocations, targetRange.EndIndex, targetRange, 1, maxSearchResults * 1, candidates); Scan(_endLocations, targetRange.EndIndex, targetRange, -1, maxSearchResults * 2, candidates); var sorted = new BMultiMap <float, Pair <ILNode, IndexRange> >(null, (p, q) => 0); foreach (var candidate in candidates) { if (!trim || sorted[candidate.Value].StartIndex < maxSearchResults) { sorted[candidate.Value].Add(candidate.Key); } } if (trim && sorted.Count > maxSearchResults) { sorted.RemoveRange(maxSearchResults, sorted.Count - maxSearchResults); } return(sorted.Select(pair => pair.Value).ToList()); }