使用 StartsWith() 时如何提高查找性能

How to improve Lookup performance when using StartsWith()

我有这样的查询:

   Lookup<String, pages>  plsBase = (Lookup<String, pages>)(Query<pages>($@"Select ...").ToLookup(s => s.ip, o => o));

我按键访问的时候速度很快,但是问题是我需要用StartsWith()来访问。 当我像下面这样使用 StartsWith() 时,性能与常规 List

相当
var pls = plsBase.Where(x => (x.Key.StartsWith(classBIp, StringComparison.Ordinal))).SelectMany(x => x).ToList();

问题是如何提高使用 StartsWith() 时的性能?

此答案假设 classBIp 是固定长度。

选项 1:中间查找 [更新]

using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;

namespace LookupTest
{
    public class Tests
    {
        [Test]
        public void IntermediateLookupTest()
        {
            var pageInfos = new Dictionary<string, string>
            {
                { "Home", "home.html" },
                { "About", "about.html" },
                { "Fineprint", "fineprint.html" },
                { "Finish", "finish.html" },
                { "Above", "above.html" }
            };

            // Corresponds to OP: plsBase = (Lookup<String, pages>)(Query<pages>($@"Select ...").ToLookup(s => s.ip, o => o));
            Lookup<string, string> plsBase = (Lookup<string, string>)pageInfos.ToLookup(k => k.Key, v => v.Value);

            Lookup<string, string> intermediateLookup = (Lookup<string, string>)pageInfos.ToLookup(k => k.Key.Substring(0, 3), v => v.Key);

            var classBIp = "Abo";

            var result = new List<string>();

            foreach (var plsBaseKey in intermediateLookup[classBIp])
            {
                result.AddRange(plsBase[plsBaseKey]);
            }

            Assert.AreEqual(2, result.Count);
            Assert.True(result.Contains("about.html"));
            Assert.True(result.Contains("above.html"));
        }
    }
}

选项 2:比较子字符串

var bipLength = classBip.Length;
var pls = plsBase.Where(x => 
    (x.Key
        .Substring(0, bipLength)
            .Equals(classBIp, StringComparison.Ordinal)))
    .SelectMany(x => x)
    .ToList();

您可能想对这两个选项进行计时,看看哪个效果更好。