Tomato
Tomato

Reputation: 153

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.

The code:

ICollection<ICollection<int>> mycollection = // instantiate with some numbers
List<List<int>> myList = myCollection;

Upvotes: 1

Views: 4470

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

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:

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

Be aware, though, that if a client calls Add or Remove or even Clear on te returned collection, this will alter the original collection if this already is a list. If it is any different type of collection - say a HastSet<T>- manipulating the returned collection won't change the original one.

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:

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

Upvotes: 6

Sean
Sean

Reputation: 62472

You can do it with Linq:

ICollection<ICollection<int>> data = ...;        
var converted = data.Select(c => c.ToList()).ToList();

Upvotes: 0

Related Questions