按列表int查询列表对象

时间:2013-11-07 02:29:12

标签: c# .net linq

我有一个对象列表(带有id)和一个列表int,查询列表对象提供列表int的最佳方法是什么。

class CommonPartRecord {
  public int Id {get;set;}
  public object Others {get;set;}
}
var listObj = new List<CommonPartRecord>();
// Load listObj
var listId = new List<int>();
// Load listId

现在选择listObj,因为这些Id包含在listId中,我目前这样做:

var filterItems = listObj.Where(x => listId.Contains(x.Id));

执行此操作的更快方法是什么? 谢谢, 于伊

1 个答案:

答案 0 :(得分:1)

var tmpList = new HashSet<int>(listId);
var filterItems = listObj.Where(x => tmpList.Contains(x.Id));

这可能会提升性能或降低性能,这在很大程度上取决于listObjlistId的大小。

您需要对其进行分析,看看您是否从中获得了任何改进。


解释提升或下降:

我将使用一些非常夸张的数字来使数学更容易,让我们说以下

  • listObj.Where(x => listId.Contains(x.Id));每行需要5秒钟。
  • listObj.Where(x => tmpList.Contains(x.Id))每行需要2秒。
  • var tmpList = new HashSet<int>(listId);需要10秒钟才能构建。

让我们绘制出处理数据需要多长时间的时间,这些时间因listObj

中的行数而异
+----------------+------------------------------+----------------------------------+
| Number of rows | Seconds to process with list | Seconds to process with hash set |
+----------------+------------------------------+----------------------------------+
|              1 |                            5 |                               12 |
|              2 |                           10 |                               14 |
|              3 |                           15 |                               16 |
|              4 |                           20 |                               18 |
|              5 |                           25 |                               20 |
|              6 |                           30 |                               22 |
|              7 |                           35 |                               24 |
|              8 |                           40 |                               26 |
+----------------+------------------------------+----------------------------------+

enter image description here

因此,您可以看到listObj是否有1到3行,您的旧方式更快,但是一旦您有4行或更多行,新方法就会更快。

(注意我完全把这些数字搞定了,我可以保证HashSet的每一行比List的每行快,但是我不能告诉你多快了。你需要测试看看你是否指向你获得更好的性能是4行或4,000行。唯一的方法就是尝试双向和测试。)

相关问题