c# - 优化通用列表 WHERE

标签 c# lambda generic-list

当 SecurityInfoMasterList 有大约 11,000 个项目并且 listClassiNode 有大约 750 个项目时,下面的语句需要大约 6 秒来生成输出。

是否有任何其他方法可以实现相同的结果但性能更好?

List<SecurityInfo> listSecurityInfo = SecurityInfoMasterList.Where(c => 
    listClassiNode.Any(d => 
        c.SX == d.Exch && c.Instrument == d.Instrument)).ToList();

我一直在尝试使用 for 循环,但没有看到太大的改进。

更新:

listClassiNode 是一个列表

[Serializable]
     public class SecurityInfo
    {
    public string SecurityID { get; set; }
    public int SecurityTypeID { get; set; }
    public string Code { get; set; }
    public string SecurityName { get; set; }
    public int DB { get; set; }
    public string ExchangeName { get; set; }
    public DateTime FirstDate { get; set; }
    public int StatusCode { get; set; }
    public long GICS { get; set; }
    public string ICB { get; set; }
    public string Sector { get; set; }
    public string IndustryGroup { get; set; }
    public string Industry { get; set; }
    public string Instrument { get; set; }
    public string TypeDescription { get; set; }
    public string SX { get; set; }
    public string GUID { get; set; }
  }



[Serializable()]
    public class ClassificationNode
    {
        public string Exch { get; set; }
        public string Instrument { get; set; }
        public string Prefix { get; set; }
        public string Name { get; set; }
        public string Level { get; set; }
    }

艾伦

最佳答案

您可以将您的 listClassiNode 转换成某种类型的 HashSet,以便查找是 O(1) 而不是 O( n).

var hash = new HashSet<string>(
    listClassiNode.Select(t => 
        string.Format("{0}_{1}", t.Exch, t.Instrument)).Distinct());

List<SecurityInfo> listSecurityInfo = SecurityInfoMasterList.Where(c => 
    hash.Contains(string.Format("{0}_{1}", c.SX, c.Instrument))
        .ToList();

上面的代码有点笨拙,string.Format 创建了一个用于 HashSet 的连接键。希望您的数据的性质不会成为问题。无论如何,我希望你明白了。

关于c# - 优化通用列表 WHERE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18626686/

相关文章:

c# - 为什么 New Relic 在慢速网络事务下列出 "/System.ServiceModel.Activation.AspNetRouteServiceHttpHandler"?

.net - VB.NET : "Statement lambdas cannot be converted to expression trees" compile time error

linq - 为什么在 foreach 中需要一个临时变量才能包含在 lambda 表达式中?

Java 8 Lambda Collectors.summingLong 多列?

c# - 将 IEnumerable<T> 转换为 JSON 对象

c# - NUnit 比较两个列表

c# - Newtonsoft 与 IDynamicMetaObjectProvider 实现反序列化类相关的问题

c# - 如何从我的 Web API 响应中删除 header ?

c# - 在 ViewModel 实体上使用 DataAnnotation 进行 Prism IDataErrorInfo 验证

java - 将具体 map 分配给通用类型 map