c# - 如何从 ICollection 转换为 IEnumerable?

标签 c# asp.net active-directory

在下面的代码中,return 语句抛出异常。

private IEnumerable<DirectoryEntry> GetDomains()
{
    ICollection<string> domains = new List<string>();

    // Querying the current Forest for the domains within.
    foreach (Domain d in Forest.GetCurrentForest().Domains)
    {
        domains.Add(d.Name);
    }

    return domains;  //doesn't work
}

这个问题可能的解决方案是什么?

最佳答案

将你的方法重新定义为

private IEnumerable<string> GetDomains()
{
    ...
}

因为您需要 string 的列表而不是 DomainsDirectoryEntry . (假设您要添加“d.Name”)

此外,使用 LINQ 会容易得多:

IEnumerable<string> domains = Forest.GetCurrentForest().Domains.Select(x => x.Name);

这将返回 IEnumerable<string> , 它不会浪费额外的内存来创建一个单独的列表。

关于c# - 如何从 ICollection 转换为 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23795165/

相关文章:

c# - 为 wp7 创建一个 pdf 阅读器

c# - 在.Net中 stub /模拟数据库

c# - 使用 yield 来推迟 Azure blob 存储调用 - c#

c# - 如何对数据库中的用户使用 Windows 身份验证

javascript - 限制 Asp :TextBox to not allow more than 6 character in it

c# - 如何将从外部登录提供程序获取的有关用户的数据获取到他的 ClaimsIdentity 中?

c# - 提高MMO游戏性能

powershell - 从 AD OU 获取 WmiObject

c# - 在服务器端连接上验证 AD 用户 PrincipalContext

.net - 如何使用 DDD 将 Active Directory 集成到 .NET 应用程序中?