本文介绍了C#:在这种情况下,我将如何过滤掉不需要的名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与C#特定问题相比,这更像是一个与语言无关的问题,但是由于它处理的是命名空间,所以我认为我会将其标记为与.NET相关.

This is more of a language-agnostic question than a C#-specific one, but since it deals with namespaces I thought I'd tag this as .NET-related.

假设您有一堆代表名称空间的字符串:

Say you have a bunch of strings that represent namespaces:

[
    "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的父级,因此也将其排除在外.这一直持续到您得到以下结果为止:

You want to filter them in such a way that any namespace that 'contains' another namespace in the collection is excluded. For example, since System contains System.Windows, it's excluded. Since System.IO is a parent of System.IO.Packaging, it's likewise excluded. This continues until you end up with this:

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

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

What would be an efficient way to filter a list this way in C#? I'm looking for a method that will look something like this:

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

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

Any help would be appreciated, thanks!

编辑:这最终对我有用:

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

这篇关于C#:在这种情况下,我将如何过滤掉不需要的名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:06