【问题标题】:C# ToList performance and alternative waysC# ToList 性能和替代方法
【发布时间】:2015-11-04 02:50:45
【问题描述】:

我有一本大字典和一个列表 (myList)。只有当我的字典中有一个具有相同标题的项目时,我才想将这些项目保留在 myList 中。问题是 titleList 的初始化需要很长时间(2-3 秒)。有没有更好的方法来做到这一点?

var dictionary = r.MyFunction.Where(a condition);
var titleList = dictionary.Select(x => x.Value.Title).ToList()

myList = productsTemp.Where(x => titleList.Contains(x.Title)).ToList();

【问题讨论】:

  • 这可能会增加一些加速的var titleList = new HashSet<string>(dictionary.Select(x => x.Value))
  • 你确定不是myList的创作需要时间吗?
  • 您是否尝试删除第二行中对ToList 方法的调用?我认为没有必要,在下一行你将使用IEnumerable<T>.Contains 方法
  • 您在创建列表时要达到的目标时间是多少?
  • 您的示例代码不完整。请提供完整的编译示例代码。例如。什么是 MyFunction (属性?什么类型的?)。没有这些信息,所有答案都只是猜测。

标签: c#


【解决方案1】:

嗯,HashSets 可以优化字符串的不同,因为列表不需要排序Getting unique items from a list

至于代码,它应该像这样工作:

    var items = r.MyFunction.Where(a condition).Select(p => p.Value.Title);
    var titleList = new HashSet<string>(items);
    myList = productsTemp.Where(x => titleList.Contains(x.Title)).ToList();

希望这会有所帮助。

编辑:构造函数调用现在在外面。

【讨论】:

  • 这不是为productsTemp 中的每个产品迭代创建一个新的HashSet&lt;T&gt;(因此是O(m*n))吗?提取构造函数调用对性能有很大帮助。
猜你喜欢
  • 2011-12-07
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多