![](/img/trans.png)
[英]C# Expand Flat List<T> to Dictionary<T,ICollection<int>>
[英]How to convert ICollection<ICollection<int>> to List<List<int>> in C#
有没有办法优雅地做到这一点? 我需要做的就是用另一个数组ICollection<ICollection<int>>
的值存储一个新变量List<List<int>>
>> ,但我找不到任何方法来做到这一点。
编码:
ICollection<ICollection<int>> mycollection = // instantiate with some numbers
List<List<int>> myList = myCollection;
对于此类问题,我有一个扩展方法,首先尝试将集合转换为列表以防止对ToList
的过时调用:
public static List<T> SafeToList<T>(this IEnumerable<T> source)
{
var list = source as List<T>;
return list ?? source.ToList();
}
现在您可以使用以下内容:
var result = myCollectionOfCollections.Select(x => x.SafeToList()).SafeToList();
如果您的 collections 可能是 arrays 并且您不关注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();
}
或单线:
public static IList<T> SafeToList<T>(this IEnumerable<T> source)
=> source as List<T> ?? source as T[] ?? (IList<T>) source.ToList();
你可以用 Linq 做到这一点:
ICollection<ICollection<int>> data = ...;
var converted = data.Select(c => c.ToList()).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.