c# - 列表集合对于 30000 个项目来说太慢了
问题描述
我使用一个包含两个项目 ID 和条形码的列表集合。该列表包含大约 30000 行。
什么时候使用下面的代码大约需要 600 毫秒。有什么办法可以让它快一点吗?
var InventoryItemID = mBarcode.Where(x => (x.Barcode == Barcode.Text))
.Select(x => x.InventoryItemID)
.First();
解决方案
尝试使用as 值进行Dictionary<K,V>
键控。Barcode
InventoryItems
我不能准确地看到你的课程,但是是这样的:
class Barcode
{
public string BarcodeText { get; set; }
public int InventoryItemId { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Create some barcodes
Barcode bc1 = new Barcode { BarcodeText = "AAA", InventoryItemId = 123 };
Barcode bc2 = new Barcode { BarcodeText = "BBB", InventoryItemId = 456 };
Barcode bc3 = new Barcode { BarcodeText = "CCC", InventoryItemId = 789 };
Dictionary<string, Barcode> dict = new Dictionary<string, Barcode>();
// Add to dictionary, keying on the barcode's text
dict.Add(bc1.BarcodeText, bc1);
dict.Add(bc2.BarcodeText, bc2);
dict.Add(bc3.BarcodeText, bc3);
// Lookup on the barcode text and get the required property
Console.WriteLine(dict["BBB"].InventoryItemId);
}
}
对于大数字,这会更快,因为在 List 上搜索是线性的,所以平均搜索时间与项目数 (N) 成正比。
字典对键的哈希值进行分区搜索,并且与 N 的二进制日志成正比。
推荐阅读
- angular - 如何摆脱 cdk-overlay-container
- r - 基于多个“高于/低于中值”的“总分”
- flutter - 缺少适用于 Android 和 iOS 的 Flutter 应用程序的 Tap-Jacking 保护
- django - 如何使用另一个模型在 django 模型中创建选择字段
- django - 将 ID 传递给 Django URL
- python - PySide6/shiboken6 的 ImportError
- mongodb - MongoDB - 在多个条件下加入
- android - 监听 WebView 中的按钮点击并在其背后实现某些逻辑
- css - 自定义字体在 react 中不起作用,提供创建 react 应用程序
- regex - 如何在 ' 中查找所有字符串但排除包含 System.debug 的行