C #: How to filter out unnecessary namespaces in this scenario?

This is more an agnostic language issue than a C # -specific one, but since it deals with namespaces, I thought I would mark it as .NET related.

Let's say you have a group 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"
]

You want to filter them in such a way as to exclude any namespace that "contains" another namespace in the collection. For example, since it Systemcontains System.Windows, it is excluded. Since it System.IOis a parent element System.IO.Packaging, it is also excluded. This continues until you finish:

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

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

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

Any help would be appreciated, thanks!


EDIT: :

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

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

, - System, - . , node ( = 1 - ).

+2

Source: https://habr.com/ru/post/1627681/


All Articles