C#:在这种情况下,如何过滤掉不需要的命名空间?
这更像是一个与语言无关的问题而不是C#特定的问题,但由于它处理命名空间,我认为我将其标记为与.NET相关。
假设您有一堆代表名称空间的字符串:
[ "System", "System.Windows", "System.Windows.Input", "System.Windows.Converters", "System.Windows.Markup", "System.Windows.Markup.Primitives", "System.IO", "System.IO.Packaging" ]
您希望以这样的方式过滤它们,即排除“包含”集合中另一个命名空间的任何命名空间。 例如,由于System
包含System.Windows
,因此将其排除。 由于System.IO
是System.IO
的父级,因此它也被排除在外。 这一直持续到你最终得到这个:
[ "System.Windows.Input", "System.Windows.Converters", "System.Windows.Markup.Primitives", "System.IO.Packaging" ]
在C#中以这种方式过滤列表的有效方法是什么? 我正在寻找一个看起来像这样的方法:
public IEnumerable FilterNamespaces(IEnumerable namespaces) {}
任何帮助将不胜感激,谢谢!
编辑:这是最终对我有用的:
public IEnumerable FilterNamespaces(IEnumerable namespaces) => namespaces.Where(current => !namespaces.Any(n => n.StartsWith($"{current}.")));
试试以下
public static IEnumerable FilterNamespaces(IEnumerable namespaces) => namespaces .Where(ns => namespaces .Where(n => n != ns) .All(n => !Regex.IsMatch(n, $@"{Regex.Escape(ns)}[\.\n]"))) .Distinct();
您可以构建一个树,其中根是System
命名空间,每个边将表示不同命名空间之间的父子关系。 然后你可以通过遍历算法找到树的所有叶子,该算法找到每个节点的等级(等级= 1的节点是叶子 – 它们没有子节点)。