如何从icollections转换为IEnumerable

本文关键字:IEnumerable 转换 icollections | 更新日期: 2023-09-27 18:04:35

在下面的代码中,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
}

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

如何从icollections转换为IEnumerable

将方法重新定义为

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

,因为你想要一个string的列表,而不是DomainsDirectoryEntry。(假设因为你添加了" d.p name ")

同样,使用LINQ:

会容易得多
IEnumerable<string> domains = Forest.GetCurrentForest().Domains.Select(x => x.Name);

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

设置域类型为IList<string>或者按照Nathan的建议去做:

private IEnumerable<string> GetDomains()
{
  return Forest.GetCurrentForest().Domains.Select(x => x.Name);
}

为将来参考,这也可以工作:

private IEnumerable<string> GetDomains()
{
  return Forest.GetCurrentForest().Domains.Cast<string>();
}

转换类型等于IEnumerable的类型

ICollection<T>继承自IEnumerable<T>,所以你可能只需要转换它:

public interface ICollection<T> : IEnumerable<T>, IEnumerable
相关文章: