WiiMaxx
WiiMaxx

Reputation: 5420

how to cast/convert a Collection<T> to an Collection<U>

is there an easy way to do this whiteout using a loops?

how my classes looks like

class T
{
    //some stuff
}

class U
{
     //some stuff

    public U(T myT)
    {
         //some stuff
    }
}

i found on my research the following method List.ConvertAll but it is only for List now i want to know if someone knows a way to achieve this for Collections.

i would prefer a generic solution but anything that solve this in a performant way.

Upvotes: 0

Views: 46

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

You can use a LINQ select for this:

var enumerableOfU = collectionOfT.Select(t => new U(t));

If you want to enumerate enumerableOfU multiple times, you should append .ToList() or .ToArray() after the Select.

Please note that this internally still uses loops, but you don't have to write it yourself.

Upvotes: 1

Related Questions