当 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/