c# - 快速查找可枚举对象中的结果

标签 c# linq optimization search

我正在尝试编写一个实用程序来查看自从我存储在数据库中的日期以来用户是否登录过 Windows。

private void bwFindDates_DoWork(object sender, DoWorkEventArgs e)
{
    UserPrincipal u = new UserPrincipal(context);
    u.SamAccountName = "WebLogin*";
    PrincipalSearcher ps = new PrincipalSearcher(u);
    var result = ps.FindAll();
    foreach (WebAccess.WebLoginUsersRow usr in webAccess.WebLoginUsers)
    {
        UserPrincipal b = (UserPrincipal)result.
            Single((a) => a.SamAccountName == usr.WEBUSER);
        if (b.LastLogon.HasValue)
        {
            if (b.LastLogon.Value < usr.MODIFYDATE)
                usr.LastLogin = "Never";
            else
                usr.LastLogin = b.LastLogon.Value.ToShortDateString();
        }
        else
        {
            usr.LastLogin = "Never";
        }
    }
}

但是性能很慢。我从中提取的用户列表有大约 150 个 Windows 用户,所以当我点击 UserPrincipal b = (UserPrincipal)result.Single((a) => a.SamAccountName == usr.CONVUSER); 每个用户需要 10 到 15 秒才能完成(单步执行我可以看到它正在执行步骤 a.SamAccountName == usr.CONVUSE 为每个人运行,所以最坏的情况正在运行O(n^2) 次)

关于提高效率的方法有什么建议吗?

最佳答案

我建议:

var result = ps.FindAll().ToList();

PrincipalSearchResult不像其他东西那样缓存,这将使您的性能水平接近 O(n)。

关于c# - 快速查找可枚举对象中的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2358416/

相关文章:

c# API 可以返回 HttpWebResponse

c# - C# 中数字文字中的下划线是什么意思?

c# - 为什么 C# 7.2 功能不能在 UWP 应用程序中编译?

c# - 等于 (LINQ) 和 == (C#) 运算符之间的区别?

c# - Linq multiple where 排序顺序

performance - 在x86汇编中将寄存器设置为零的最佳方法是什么:xor,mov或and?

c# - 将值绑定(bind)到复杂类型

c# - 使用 LINQ C# 从 List<Class> 获取最长的字符串

swift - 将许多不同对象保存到核心数据的最佳方法

algorithm - 评估二元标量积 mod 2 的最有效方法