C#嵌套foreach循环优化

C#嵌套foreach循环优化

本文介绍了C#嵌套foreach循环优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的foreach循环,我真的需要削减的计算时间。每个集合在大约50名成员,所以推断是巨大的。我已经看了很多关于信息的SelectMany,但我仍然不能完全确定如何使用它,或者如果它是正确的解决方案。

I've got a nested foreach loop that I really need to cut the computation time on. Each collection is at about 50 members, so the extrapolation is huge. I've looked at a lot of information about SelectMany, but I'm still not entirely sure how to use it, or if it's the correct 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.
    }
  }
}

在此先感谢!

推荐答案

使用查找(如字典),以增加检查类型名称的速度:

Use a lookup (such as a dictionary) to increase the speed of checking for 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.
    }
  }
}

您也应该检查哪些的2集(的StringList assemblyTypes )可能要大一些。你通常希望较大的一个,以便减少迭代次数被转换到查找

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

这篇关于C#嵌套foreach循环优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:30