C#: Convert List to List

1 comment

If I have objects that implement or inherits from a parent, I can cast them implicitly to their base class:

Here KorrespondanseParameter implements IPurrefrister:

KorrespondanseParameter k=new KorrespondanseParameter();

IPurrefrister deadline= k;

or even:

IPurrefrister deadline= new KorrespondanseParameter();

Same with this where NytegningAktoerRetur inherits from NytegningRetur:

NytegningAktoerRetur nar=new NytegningAktoerRetur();

NytegningRetur obj= nar;

Often I have some kind of List of objects that I want to cast to it something else.

One could think that this should work:

List< KorrespondanseParameter> list=new List< KorrespondanseParameter>();

List< IPurrefrister> plist=list;

or explicit:

List< IPurrefrister> plist= (List< IPurrefrister>) list;

neither compiles.

Solution with delegates:

List<KorrespondanseParamer> to List<IPurrefrister> where

public static List<IPurrefrister> LagIPurrefrister(List<KorrespondanseParameter> korr)

{

    if (korr != null)

    {

    return korr.ConvertAll<IPurrefrister>(

        delegate(KorrespondanseParameter k)

        {

            return k;

        });

    }

    else

    {

        return null;

    }

}

lambda:

IEnumerable<NytegningAktoerRetur> to List<NytegningRetur>

List<NytegningRetur> liste = TilbudsListe.ToList().ConvertAll<NytegningRetur>(t=> t);

Nice and short :)

rgds

Henri

Posted via email from Henris blogg

1 comment :

  1. Oops.
    I just found a sweet little extension method built right into the .Net framework:

    IEnumerable.Cast<T>

    meaning the above could be written:
    List<NytegningRetur> list = TilbudsListe.Cast<NytegningRetur>();

    You won't find it much easier.. :))

    ReplyDelete