首页 文章

从IEnumerable转换为List [duplicate]

提问于
浏览
212

这个问题在这里已有答案:

我想从 IEnumerable<Contact> 转换为 List<Contact> . 我怎样才能做到这一点?

5 回答

  • 16

    您可以使用LINQ非常简单地完成此操作 .

    确保使用它位于C#文件的顶部:

    using System.Linq;
    

    然后使用ToList扩展方法 .

    例:

    IEnumerable<int> enumerable = Enumerable.Range(1, 300);
    List<int> asList = enumerable.ToList();
    
  • 5

    如果你正在使用常规的旧 System.Collections.IEnumerable 而不是 IEnumerable<T> ,你可以使用 enumerable.Cast<object>().ToList()

  • 4

    如果您正在使用 System.Collections.IEnumerable 的实现,则可以执行以下操作将其转换为 List . 以下使用Enumerable.Cast方法将 IEnumberable 转换为Generic List .

    //ArrayList Implements IEnumerable interface
    ArrayList _provinces = new System.Collections.ArrayList();
    _provinces.Add("Western");
    _provinces.Add("Eastern");
    
    List<string> provinces = _provinces.Cast<string>().ToList();
    

    如果您使用的是通用版 IEnumerable<T> ,则转换很简单 . 既然两者都是泛型,你可以这样做,

    IEnumerable<int> values = Enumerable.Range(1, 10);
    List<int> valueList = values.ToList();
    

    但是如果 IEnumerable 为null,当你尝试将其转换为 List 时,你会得到 ArgumentNullException ,表示Value不能为null .

    IEnumerable<int> values2 = null;
    List<int> valueList2 = values2.ToList();
    

    enter image description here

    因此,如other answer中所述,请记住在将其转换为 List 之前进行 null 检查 .

  • 143

    我为此使用了扩展方法 . 我的扩展方法首先检查枚举是否为null,如果是,则创建一个空列表 . 这允许您对其进行foreach而无需显式检查null .

    这是一个非常人为的例子:

    IEnumerable<string> stringEnumerable = null;
    StringBuilder csv = new StringBuilder();
    stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(","));
    

    这是扩展方法:

    public static List<T> ToNonNullList<T>(this IEnumerable<T> obj)
    {
        return obj == null ? new List<T>() : obj.ToList();
    }
    
  • 351

    其他方式

    List<int> list=new List<int>();
    
    IEnumerable<int> enumerable =Enumerable.Range(1, 300);  
    
    foreach (var item in enumerable )  
    {     
      list.add(item);  
    }
    

相关问题