private static RouteResolutionResult FindMostSpecificRoute(IEnumerable<RouteResolutionResult> routes)
{
RouteResolutionResult bestMatch = default(RouteResolutionResult);
var otherMatches = new List<RouteResolutionResult>();
foreach (var route in routes)
{
if (bestMatch == null)
{
bestMatch = route;
continue;
}
if (route.VariableCount > bestMatch.VariableCount)
{
otherMatches.Clear();
bestMatch = route;
continue;
}
if (route.Priority < bestMatch.Priority)
{
continue;
}
if (route.VariableCount == bestMatch.VariableCount)
{
// Choose
// /product-lines/{productId}/{lineNumber}
// over
// /products/{productId}/product-lines/{lineNumber}
// (shortest one)
if (route.PathLength < bestMatch.PathLength)
{
otherMatches.Add(bestMatch);
bestMatch = route;
}
else
{
otherMatches.Add(route);
}
}
}
// We may find several different routes {code}/{id} and {code}/{name} having the same number of variables.
// Such case will be handled by the next check.
return bestMatch == null || otherMatches.All(r => r.HasSameVariables(bestMatch))
? bestMatch
: null;
}