[英]How to convert ICollection<ICollection<int>> to List<List<int>> in C#
Is there any way to elegantly do this?有没有办法优雅地做到这一点? All I need to do is store a new variable
List<List<int>>
with values of another array ICollection<ICollection<int>>
, but I can't find any way to do this.我需要做的就是用另一个数组
ICollection<ICollection<int>>
的值存储一个新变量List<List<int>>
>> ,但我找不到任何方法来做到这一点。
The code:编码:
ICollection<ICollection<int>> mycollection = // instantiate with some numbers
List<List<int>> myList = myCollection;
I have an extension-method for this kind of problem, that first tries to cast the collection into a list to prevent obsolete calls to ToList
:对于此类问题,我有一个扩展方法,首先尝试将集合转换为列表以防止对
ToList
的过时调用:
public static List<T> SafeToList<T>(this IEnumerable<T> source)
{
var list = source as List<T>;
return list ?? source.ToList();
}
Now you can use the following:现在您可以使用以下内容:
var result = myCollectionOfCollections.Select(x => x.SafeToList()).SafeToList();
If your collections may be arrays and you do not focus on List<T>
as outcome of the method you can also use the more generic interface IList<T>
instead:如果您的 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();
}
or as one-liner:或单线:
public static IList<T> SafeToList<T>(this IEnumerable<T> source)
=> source as List<T> ?? source as T[] ?? (IList<T>) source.ToList();
You can do it with Linq:你可以用 Linq 做到这一点:
ICollection<ICollection<int>> data = ...;
var converted = data.Select(c => c.ToList()).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.