views:

164

answers:

2
List<string> nameSpaceSuffixes = GetSuffixes();

foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            foreach(var suffix in nameSpaceSuffixes)
            {
                if (assembly.GetName().Name.EndsWith(suffix))
                    Register(container, assembly, suffix);
            }
        }
+1  A: 

This may not be the most efficient but:

 AppDomain.CurrentDomain
          .GetAssemblies()
          .SelectMany(assembly => nameSpaceSuffixes.Select(suffix =>
                                  new { Assembly = assembly, Suffix = suffix }))   
          .Where(anon => anon.Assembly.GetName().Name.EndsWith(anon.Suffix))       
          .ToList()
          .ForEach(anon => Register(container, anon.Assembly, anon.Suffix);
Ani
+4  A: 

As a query expression:

var query = from assembly in AppDomain.CurrentDomain.GetAssemblies()
            from suffix in namespaceSuffixes
            where assembly.GetName().Name.EndsWith(suffix)
            select new { assembly, suffix };

foreach (var result in query)
{
    Register(container, result.assembly, result.suffix);
}

I haven't gone down Ani's route of using List<T>.ForEach - I personally prefer to use a normal foreach statement. LINQ is great for the declarative querying; foreach is godo for the imperative action taken on each element.

Note that my query expression is almost equivalent to Ani's dot notation; the C# compiler would use a slightly different overload of SelectMany, that's all. In this particular case I think the query expression is easier to understand; in simpler cases I prefer dot notation.

Jon Skeet
@Jon Skeet: I agree about not putting side-effects in a query, it was an attempt to do it all in one-line. I also agree that the query syntax is cleaner in this case. To be honest, I've never been able to get comfortable with it. Any suggestions for how best to master query syntax for someone who already knows the extension-method syntax?
Ani
@Ani: It depends on why you're uncomfortable. Simply because it doesn't look like "normal" C#? Or because you're not sure what the compiler does with it? It's a real boon for group by and joins, IMO.
Jon Skeet
@Jon Skeet: I'm not sure what the compiler does with it.It's really non-obvious to me that the `where` clause on the third line is operating on a particular member of the cartesian product of `GetAssemblies()` and `namespacesuffixes`, whereas I have no problems doing that myself with a `SelectMany`.
Ani
hhehe awesome. you guys rock. I like the advice for using linq for declarative querying, then handle the imperative stuff separately.
djmc
+1 those who always use `List<T>.ForEach` are one-line-code fans. But I'd prefer to divide it to two parts which brings more readable code and better expression of "what do I want to do".
Danny Chen