C # Nested foreach loop optimization

I have a nested foreach loop that I really need to reduce the computation time. Each collection has about 50 participants, so the extrapolation is huge. I looked at a lot of information about SelectMany, but I'm still not quite sure how to use it, or if this is the right solution.

List<string> StringList; //Populated in previous code Type[] assemblyTypes = RandomAssembly.GetTypes(); foreach (String name in StringList) { foreach (Type at in assemblyTypes) { if (name == at.Name) { //Do stuff. } } } 

Thanks in advance!

+4
source share
5 answers

Use a search (for example, a dictionary) to increase the speed of checking a type name:

 List<string> StringList; //Populated in previous code Dictionary<string,Type> assemblyTypes = RandomAssembly.GetTypes() .ToDictionary(t => t.Name, t => t); foreach (String name in StringList) { if (assemblyTypes.ContainsKey(name)) { //Do stuff. } } } 

You should also check which of the two collections ( StringList or assemblyTypes ) is likely to be larger. Usually you want a larger one to be converted to lookup in order to reduce the number of iterations.

+4
source

Load the type [] into the dictionary or HashSet (depending on your version of .NET) and then the inner loop will disappear.

 List<string> StringList; //Populated in previous code Type[] assemblyTypes = RandomAssembly.GetTypes(); Dictionary<String,Type> typesHash = new Dictionary<String,Type>(); foreach ( Type type in assemblyTypes ) { typesHash.Add( type.Name, type ); } foreach (String name in StringList) { Type type = null; if ( typesHash.TryGetValue( name, out type ) ) { // do something with type } } 
+2
source

You can try something like:

 assemblyTypes.Where(x => StringList.Contains(x.Name)); 

Keep in mind that this is case sensitive and ignores spaces, so you will need to add a case review or trim if this is a problem.

Edit: (loop usage example)

 foreach (Type item in assemblyTypes.Where(x => StringList.Contains(x.Name))) { // Do stuff } 
0
source

If your array / list contains many elements, you can try using the ForEach Parallel Loop .

0
source

The best optimization may be to request not a name, but instead for an implemented interface.

Make sure you optimize the correct problem / piece of your code.

0
source

All Articles