gpt4 book ai didi

c# - 在 .net 2.0 中将 IEnumerable 转换为 List

转载 作者:太空狗 更新时间:2023-10-30 00:08:08 25 4
gpt4 key购买 nike

我需要转换 IEnumerableList<string> .其中一种方法是通过它进行迭代并将每个对象添加到列表中,但这个过程非常耗时。有没有其他方法可以做到这一点。任何帮助将不胜感激。

最佳答案

您可以将枚举直接传递给 constructor一个新的 List<string>实例:

List<string> list = new List<string>(yourEnumerable);

或者您可以使用 AddRange 方法:

List<string> list = new List<string>();
list.AddRange(yourEnumerable);

此答案假设您实际上已经拥有一个 IEnumerable<string> .
如果不是这种情况,您唯一的选择就是循环:

List<string> list = new List<string>();
foreach(object item in yourEnumerable)
list.Add(item.ToString());

顺便说一句:你是说:

one of the way is to itearte through this and add each object to a list but this process is vary time consuming

在任何情况下都需要迭代可枚举。你还能如何获得所有值(value)?在我给你的前两个示例代码中,枚举是在 List<T> 内部执行的。类,但它仍在发生。

关于c# - 在 .net 2.0 中将 IEnumerable 转换为 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12746826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com