将 ICollection<T> 转换为列表<string>

问题描述 投票:0回答:2

是否可以轻松有效地将 ICollection 接口的实例转换为 List? 无论 T 的类型如何,源集合的每个元素都必须转换为字符串(我想使用 ToString() 方法),然后添加到目标对象中。 有没有一种方法可以有效地做到这一点(无需创建第三个临时对象并对其进行迭代)?

c# string list casting icollection
2个回答
0
投票

最有效的方法是预先创建与集合大小相同的列表,然后使用

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));

-1
投票

这符合您的目的吗?

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});
© www.soinside.com 2019 - 2024. All rights reserved.