首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用c#中的数据结构算法从检索记录

使用c#中的数据结构算法从检索记录
EN

Stack Overflow用户
提问于 2018-11-26 17:24:02
回答 1查看 294关注 0票数 0

我需要获取活动目录记录并插入SQL数据库中。大约有10,000条记录。我使用了这个代码:

代码语言:javascript
复制
List<ADUser> users = new List<ADUser>();

DirectoryEntry entry = new DirectoryEntry("LDAP://xyz.com");
ADUser userToAdd = null;

IList<string> dict = new List<string>();               

DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(&(objectClass=user))";
search.PropertiesToLoad.Add("samaccountname");
search.PageSize = 1000;

foreach (SearchResult result in search.FindAll())
{
    DirectoryEntry user = result.GetDirectoryEntry();

    if (user != null && user.Properties["displayName"].Value!=null)
    {
        userToAdd = new ADUser
                    {
                        FullName = Convert.ToString(user.Properties["displayName"].Value),
                        LanId = Convert.ToString(user.Properties["sAMAccountName"].Value)
                    };

        users.Add(userToAdd);
    }
}

如何从速度和空间复杂度的角度优化上述代码?是否可以使用二叉树中的遍历,因为结构看起来类似于二叉树。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-26 18:09:21

DirectorySearcher.FindAll()返回的列表只是一个列表。所以你不能比你现在更好地穿越它。

要优化这一点,不要使用GetDirectoryEntry()。这是在做两件事:

  1. 向AD提出另一个网络请求,这是不必要的,因为搜索可以返回任何您想要的属性,以及
  2. 占用内存,因为所有这些DirectoryEntry对象都将留在内存中,直到调用Dispose()或GC有时间运行为止(直到循环结束,它才会运行)。

首先,将displayName添加到PropertiesToLoad中以确保返回。然后可以使用result.Properties[propertyName][0]访问每个属性。使用这种方法,每个属性都作为数组返回,即使它是AD中的单个值属性,因此您需要[0]

另外,如果您的应用程序在此搜索完成后仍处于打开状态,请确保您在Dispose()上调用了从FindAll()中提取出来的SearchResultCollection。在FindAll()的文档中,“备注”部分表示如果不这样做,可能会有内存泄漏。或者,您可以将它放在using块中:

代码语言:javascript
复制
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(&(objectClass=user))";
search.PropertiesToLoad.Add("sAMAccountName");
search.PropertiesToLoad.Add("displayName");
search.PageSize = 1000;
using (SearchResultCollection results = search.FindAll()) {
    foreach (SearchResult result in results) {
        if (result.Properties["displayName"][0] != null) {
            userToAdd = new ADUser {
                FullName = (string) result.Properties["displayName"][0],
                LanId = (string) result.Properties["sAMAccountName"][0]
            };

            users.Add(userToAdd);
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53486150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档