Search code examples
c#loopsreflection.net-assembly

C# get all string combinations between 2 arrays


I have 2 string arrays:

string[] baseAssemblyNames

For instance ['Core', 'Web', 'Data']

string[] projectAssemblyNames

For instance ['Project1', 'Project2']

Result:

['Project1.Core', 'Project1.Web', 'Project1.Data', 'Project2.Core', 'Project2.Web', 'Project2.Data']

I want all combinations between these 2, now I am using 2 foreach to iterate and combine them.

foreach(var projectAsm in projectAssemblyNames)
{
    foreach(var baseAsm in baseAssemblyNames)
    {
        try
        {
            var asm = Assembly.Load($"{projectAsm}.{baseAsm}");
            asmList.Add(asm);
        }
        catch { }
    }
}

Is there a better solution for this in terms of performance when we have a lot of projects where we want to load the assembly for scanning?


Solution

  • Clean approach with LINQ ;)

    var assemblies = projectAssemblyNames
        .Join(baseAssemblyNames, p => 1, b => 1, (p, b) => $"{p}.{b}")
        .Select(Load)
        .Where(assembly => assembly != null)
        .ToList();
    
    Assembly Load(string assembly) 
    {
        try
        {
            return Assembly.Load(assembly);
        }
        catch 
        { 
            return null; // Not found
        }
    }