有没有办法优雅地做到这一点?我需要做的就是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)
我有一个针对此类问题的扩展方法,它首先尝试将集合转换为列表以防止对以下内容的过时调用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)