是否可以轻松有效地将 ICollection 接口的实例转换为 List? 无论 T 的类型如何,源集合的每个元素都必须转换为字符串(我想使用 ToString() 方法),然后添加到目标对象中。 有没有一种方法可以有效地做到这一点(无需创建第三个临时对象并对其进行迭代)?
最有效的方法是预先创建与集合大小相同的列表,然后使用
AddRange
和 LINQ 添加字符串。
var l = new List<string>(yourCollection.Count);
l.AddRange(yourCollection.Select(i => i.ToString()));
// or if you have nulls
l.AddRange(yourCollection.Select(i => i?.ToString()).Where(s => s != null));
这符合您的目的吗?
using System.Collections.Generic;
using System.Linq;
public static List<string> Convert<T>(ICollection<T> input){
return input
.Select(x => x?.ToString())
.OfType<string>()
.ToList();
}
用途:
List<string> list = Convert(new int[] {1, 2, 3});