检查通用列表内容的最佳方法

Joh*_*dol 3 .net c# generics performance

我必须处理一些使用通用列表来存储自定义对象集合的代码.

然后它执行类似下面的操作来检查集合中的给定对象是否存在并执行某些操作(如果是):

List<CustomObject> customObjects;
//fill up the list
List<CustomObject> anotherListofCustomObjects;
//fill it up

//...

foreach (CustomObject myCustomObject in customObjects)
{
   if (anotherListofCustomObjects.Contains(myCustomObject))
   {
      //do stuff
   }
}
Run Code Online (Sandbox Code Playgroud)

问题是永远处理7000个这样的对象.

这不是我的代码 - 我只是试图提出改进它的选项 - 在我看来,使用字典来获取密钥更快,而不是像上面那样循环遍历整个集合.

建议?

Fra*_*uma 9

除了字典之外,另一种方法是,如果你在.NET 3.5上,使用Linq来对象和相交:

foreach(CustomObject c in customObjects.Intersect(anotherListOfCustomObjects))
{
    // do stuff.
}
Run Code Online (Sandbox Code Playgroud)

根据反射器,它使用基于散列的集合来执行序列的交集.