处理列表中的路由值
本文关键字:路由 列表 处理 | 更新日期: 2023-09-27 18:06:40
我正在处理一个路线映射器,我有点偏离轨道。我得到了一个大的路由表,如下所示:
sourceUrl -> destinationUrl
- a -> b
- y -> a
- q -> b
- d -> x
- b -> d
- r -> q
- c -> b
如果我选择了最后一个节点(d -> x),我希望显示所选节点的正确路由或相关路由。该表如下所示:
- y -> a
- a -> b
- c -> b
- r -> q
- q -> b
- b -> d
现在,我有一个递归方法返回一个列表,但是我不能得到正确的顺序。我现在的是:
public List<RedirectNode> FindByDestinationUrl(string destinationUrl)
{
List<RedirectNode> nodeList = new List<RedirectNode>();
List<RedirectNode> temporalList = new List<RedirectNode>();
List<RedirectNode> helperList = new List<RedirectNode>();
try
{
nodeList = _redirectManagerRepository.FindByDestinationUrl(destinationUrl);
helperList = nodeList;
if (nodeList.Count != 0)
{
foreach (RedirectNode node in nodeList)
{
temporalList = FindByDestinationUrl(node.SourceUrl);
if (temporalList != null)
{
helperList.AddRange(temporalList);
helperList.Reverse();
}
}
}
}
catch(Exception ex)
{
nodeList = null;
LoggingFactory.GetLogger().Log(CLASS + "FindByDestinationUrl. Error. " + ex.Message.ToString());
}
nodeList = helperList;
return nodeList;
}
我收到以下路由:
- a -> b
- c -> b
- q -> b
- y -> a
- b -> d
如果您使用简单的完全递归方式(https://dotnetfiddle.net/H2LAsr),则返回:
- y -> a
- a -> b
- r -> q
- q -> b
- c -> b
- b -> d
- d -> x
//key is target, values are the sources
private static readonly ConcurrentDictionary<string, HashSet<string>> targetMap = new ConcurrentDictionary<string, HashSet<string>>();
private static void Add(string source, string target)
{
var node = targetMap.GetOrAdd(target, new HashSet<string>());
node.Add(source);
}
public static IEnumerable<KeyValuePair<string, string>> FindTarget(string destination, bool recursive = true)
{
HashSet<string> node;
if (targetMap.TryGetValue(destination, out node))
{
foreach (var source in node)
{
if (recursive)
{
foreach (var child_route in FindTarget(source))
{
yield return child_route;
}
}
yield return new KeyValuePair<string, string>(source, destination);
}
}
}
public static void Main()
{
Add("a", "b");
Add("y", "a");
Add("q", "b");
Add("d", "x");
Add("b", "d");
Add("r", "q");
Add("c", "b");
foreach (var route in FindTarget("x"))
{
Console.WriteLine("{0} -> {1}", route.Key, route.Value);
}
}