【发布时间】:2010-05-24 14:36:17
【问题描述】:
我是一个完整的 LINQ 新手,所以我不知道我的 LINQ 是否不适合我需要做的事情,或者我对性能的期望是否太高。
我有一个对象的 SortedList,以 int 为键; SortedList 而不是 SortedDictionary,因为我将使用预先排序的数据填充集合。我的任务是找到确切的密钥,或者如果没有确切的密钥,则找到具有下一个更高值的密钥。如果搜索的列表太高(例如最高键是 100,但搜索 105),返回 null。
// The structure of this class is unimportant. Just using
// it as an illustration.
public class CX
{
public int KEY;
public DateTime DT;
}
static CX getItem(int i, SortedList<int, CX> list)
{
var items =
(from kv in list
where kv.Key >= i
select kv.Key);
if (items.Any())
{
return list[items.Min()];
}
return null;
}
给定一个包含 50,000 条记录的列表,调用 getItem 500 次大约需要一秒半。调用它 50,000 次需要 2 分钟以上。这个性能似乎很差。我的 LINQ 不好吗?我期待太多了吗?我应该滚动自己的二进制搜索功能吗?
【问题讨论】:
-
标准的
List类其实内置了BinarySearch方法,可以使用;请参阅下面的答案。 -
tzaman 建议使用内置的
BinarySearch方法是正确的;只是使用List<T>.BinarySearch不是可行的方法,因为它需要将您的密钥放在List<T>中。我已经发布了一个答案,其中包括任何IList<T>(这包括SortedList<TKey, TValue>.Keys属性)上的扩展方法的代码,直接取自微软的二进制搜索实现。您可能会发现它很有用。
标签: c# linq sortedlist sorteddictionary