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); }
source share