Converting from IEnumerable to List
本问题已经有最佳答案,请猛点这里访问。
我想从
您可以使用LINQ非常简单地完成此操作。
确保使用它位于C#文件的顶部:
1 | using System.Linq; |
然后使用
例:
1 2 | IEnumerable<int> enumerable = Enumerable.Range(1, 300); List<int> asList = enumerable.ToList(); |
如果您使用常规的旧
如果您正在使用
1 2 3 4 5 6 | //ArrayList Implements IEnumerable interface ArrayList _provinces = new System.Collections.ArrayList(); _provinces.Add("Western"); _provinces.Add("Eastern"); List<string> provinces = _provinces.Cast<string>().ToList(); |
如果您使用的是通用版
1 2 | IEnumerable<int> values = Enumerable.Range(1, 10); List<int> valueList = values.ToList(); |
但是如果
1 2 | IEnumerable<int> values2 = null; List<int> valueList2 = values2.ToList(); |
因此,如其他答案中所述,请记住在将其转换为
其他方式
1 2 3 4 5 6 7 8 | List<int> list=new List<int>(); IEnumerable<int> enumerable =Enumerable.Range(1, 300); foreach (var item in enumerable ) { list.add(item); } |
我为此使用了扩展方法。我的扩展方法首先检查枚举是否为null,如果是,则创建一个空列表。这允许您对其进行foreach而无需显式检查null。
这是一个非常人为的例子:
1 2 3 | IEnumerable<string> stringEnumerable = null; StringBuilder csv = new StringBuilder(); stringEnumerable.ToNonNullList().ForEach(str=> csv.Append(str).Append(",")); |
这是扩展方法:
1 2 3 4 | public static List< T > ToNonNullList< T >(this IEnumerable< T > obj) { return obj == null ? new List< T >() : obj.ToList(); } |