繁体   English   中英

C#:在这种情况下,如何过滤掉不需要的命名空间?

[英]C#: How would I filter out the unneeded namespaces in this scenario?

这更像是一个语言无关的问题,而不是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.Packaging ,它也排除在外。 这一直持续到你最终得到这个:

[
    "System.Windows.Input",
    "System.Windows.Converters",
    "System.Windows.Markup.Primitives",
    "System.IO.Packaging"
]

在C#中以这种方式过滤列表的有效方法是什么? 我正在寻找一个看起来像这样的方法:

public IEnumerable<string> FilterNamespaces(IEnumerable<string> namespaces) {}

任何帮助将不胜感激,谢谢!


编辑:这是最终对我有用的:

public IEnumerable<string> FilterNamespaces(IEnumerable<string> namespaces) =>
    namespaces.Where(current => !namespaces.Any(n => n.StartsWith($"{current}.")));

试试以下

 public static IEnumerable<string> FilterNamespaces(IEnumerable<string> namespaces)
 => namespaces
  .Where(ns => namespaces
    .Where(n => n != ns)
      .All(n => !Regex.IsMatch(n, $@"{Regex.Escape(ns)}[\.\n]")))
  .Distinct();   

您可以构建一个树,其中根是System命名空间,每个边将表示不同命名空间之间的父子关系。 然后你可以通过遍历算法找到树的所有叶子,该算法找到每个节点的等级(等级= 1的节点是叶子 - 它们没有子节点)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM