How to get all namespaces inside a namespace recursively

Simply put, I want all the namespaces in the project to be recursive, and the classes are available in all the namespaces found earlier.

var namespaces = assembly.GetTypes() .Select(ns => ns.Namespace); 

I use this part earlier to get namespaces in string format. But now I got to know the basic namespaces.

+4
source share
1 answer

It looks like you might need Lookup from the namespace to the class:

 var lookup = assembly.GetTypes().ToLookup(t => t.Namespace); 

Or, alternatively (and very similar), you can use GroupBy :

 var groups = assembly.GetTypes().GroupBy(t => t.Namespace); 

For instance:

 var groups = assembly.GetTypes() .Where(t => t.IsClass) // Only include classes .GroupBy(t => t.Namespace); foreach (var group in groups) { Console.WriteLine("Namespace: {0}", group.Key); foreach (var type in group) { Console.WriteLine(" {0}", t.Name); } } 

However, it is not clear what you are after. This will give you classes in each namespace, but I don't know if this is really what you are looking for.

Two points to consider:

  • There is nothing recursive about it.
  • Namespaces do not actually form a hierarchy with respect to the CLR. There is no such thing as a β€œbase” namespace. C # itself has some rules about this, but as far as the CLR is concerned, there is no such thing as a "parent" namespace.

If you really want to switch from "Foo.Bar.Baz" to "Foo.Bar" and "Foo", you can use something like:

 while (true) { Console.WriteLine(ns); int index = ns.LastIndexOf('.'); if (index == -1) { break; } ns = ns.Substring(0, index); } 
+4
source

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


All Articles