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

标签 c# .net lookup

我有一个这样的查找:

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

当我通过按键访问它时速度非常快,但问题是我需要使用 StartsWith() 来访问它。 当我像下面一样使用 StartsWith() 时,性能与常规列表相当

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();

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

关于c# - 使用 StartsWith() 时如何提高查找性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61073644/

相关文章:

c# - 使用异常处理错误流程?

c# - 锐化操作会产生对比度不正确的输出

c# - DataGridView 中的单元格验证防止取消按钮触发

c# - 表示 C# 中某些类型的对象

c# - VB.NET 中的字符串包含 IgnoreCase

c# - 使用 Jira 进行 ASP.NET MVC OAuth 身份验证?

.net - 编写正则表达式来捕获外括号之间的文本

Tomcat 6 和 DNS 查找

sql - 在 SSIS 的查找中使用变量

data-structures - 多键查找数据结构