如何在 C# 中将 ICollection<ICollection<int>> 转换为 List<List<int>>

Tom*_*ato 1 c#

有没有办法优雅地做到这一点?我需要做的就是List<List<int>>用另一个数组的值存储一个新变量ICollection<ICollection<int>>,但我找不到任何方法来做到这一点。

编码:

ICollection<ICollection<int>> mycollection = // instantiate with some numbers
List<List<int>> myList = myCollection;
Run Code Online (Sandbox Code Playgroud)

Him*_*ere 5

我有一个针对此类问题的扩展方法,它首先尝试将集合转换为列表以防止对以下内容的过时调用ToList

public static List<T> SafeToList<T>(this IEnumerable<T> source)
{
    var list = source as List<T>;
    return list ?? source.ToList();
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用以下内容:

var result = myCollectionOfCollections.Select(x => x.SafeToList()).SafeToList();
Run Code Online (Sandbox Code Playgroud)

如果您的集合可能是数组并且您不关注List<T>方法的结果,您也可以使用更通用的接口IList<T>

public static IList<T> SafeToList<T>(this IEnumerable<T> source)
{
    var list = source as List<T>;
    var array = source as T[];
    return list ?? array ?? source.ToList();
}
Run Code Online (Sandbox Code Playgroud)

或作为单线:

public static IList<T> SafeToList<T>(this IEnumerable<T> source)
    => source as List<T> ?? source as T[] ?? (IList<T>) source.ToList();
Run Code Online (Sandbox Code Playgroud)

  • 这种方法的缺点是它要么创建一个新列表,要么在转换后返回现有列表。这意味着如果调用者修改结果,那么他们可能会修改原始序列,也可能不会,具体取决于输入类型。 (4认同)