首页 > 解决方案 > 列表集合对于 30000 个项目来说太慢了

问题描述

我使用一个包含两个项目 ID 和条形码的列表集合。该列表包含大约 30000 行。

什么时候使用下面的代码大约需要 600 毫秒。有什么办法可以让它快一点吗?

var InventoryItemID = mBarcode.Where(x => (x.Barcode == Barcode.Text))
                              .Select(x => x.InventoryItemID)
                              .First();

标签: c#list

解决方案


尝试使用as 值进行Dictionary<K,V>键控。BarcodeInventoryItems

我不能准确地看到你的课程,但是是这样的:

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 的二进制日志成正比。


推荐阅读