It sounds like you might want a Lookup from namespace to class:
var lookup = assembly.GetTypes().ToLookup(t => t.Namespace);
Or alternatively (and very similarly) you could use GroupBy:
var groups = assembly.GetTypes().GroupBy(t => t.Namespace);
For example:
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's not entirely clear whether that's what you're after. That will get you the classes in each namespace, but I don't know whether that's really what you're looking for.
Two points to bear in mind:
- There's nothing recursive about this
- Namespaces don't really form a hierarchy, as far as the CLR is concerned. There's no such thing as an "underlying" namespace. The C# language itself does have some rules about this, but as far as the CLR is concerned, there's no such thing as a "parent" namespace.
If you really want to go from "Foo.Bar.Baz" to "Foo.Bar" and "Foo" then you can use something like:
while (true) { Console.WriteLine(ns); int index = ns.LastIndexOf('.'); if (index == -1) { break; } ns = ns.Substring(0, index); }