【问题标题】:C#: How would I filter out the unneeded namespaces in this scenario?C#:在这种情况下,我将如何过滤掉不需要的命名空间?
【发布时间】:2016-05-17 10:13:29
【问题描述】:

这更像是一个与语言无关的问题,而不是特定于 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.IOSystem.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}.")));

【问题讨论】:

    标签: c# .net namespaces


    【解决方案1】:

    尝试关注

     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();   
    

    【讨论】:

    • 感谢您的回答!不过对于SysSystem 这样的命名空间不会出现故障吗? SystemSys 开头,但它们不相关。
    • 真的很不错。它工作正常。但是如果有两个同名的包(System.IO.Packaging),就会出现问题。它会同时返回。但是您可以通过对结果调用 Distinct 来解决此问题。
    • tchelidze:对不起,如果我是无知的,但如果将它们插入到正则表达式中,命名空间中的点是否也会引起问题? (因为.是一个特殊字符)
    • @BewarSalah 对,简单的解决方案是将Distinct() 放在查询的末尾。
    • tchelidze:this 之类的东西会返回 true,因为 . 匹配正则表达式中的单个字符。你将不得不以某种方式逃避这个点。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      相关资源
      最近更新 更多