How to convert a nested object from one type to another

I have a C # object with a structure like

class Source 
{
    public int Id {get; set;}
    public List<Source> Children {get; set;}
}

      

I want to convert an object of type Source

(with unknown number Children

) to an object of typeDestination

class Destination
{
    public int key {get; set;}
    public List<Destination> nodes {get; set;}
}

      

Is there a way I can do this using LINQ

, or do I need to iterate over everything and display it.

+3


source to share


3 answers


You can do something recursive:



public class Source
{
    public int Id { get; set; }
    public List<Source> Children { get; set; }

    public Destination GetDestination()
    {
        return new Destination
        {
            nodes = Children.Select(c => c.GetDestination()).ToList(),
            key = Id
        };
    }
}

      

+4


source


You can do it:



    List<A> alist = new List<A>();
    List<B> blist = alist.Select(a => new B()).ToList();


    public class A
    {}

    public class B
    {}

      

0


source


Maybe try adding a constructor to the Destination class that takes the source as a parameter:

class Destination
{
    public int key {get; set;}
    public List<Destination> nodes {get; set;}

    public Destination(Source source)
    {
        Key = source.Id;
        Nodes = source.Select(s => new Destination(s)).ToList();
    }
}

      

Then do:

var destinations = sources.Select(s => new Destination(s)).ToList();

      

This could go on forever, may not have tried it.

0


source







All Articles