Garima
Garima

Reputation: 441

How to convert nested object from one type to another

I have a C# object with 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 of Children) to object of type Destination

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 have to loop through all and map it.

Upvotes: 4

Views: 1853

Answers (3)

kd_
kd_

Reputation: 66

Maybe try adding a constructor to the Destination class that accepts a 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 run forever maybe, haven't tried it.

Upvotes: 0

Simon Karlsson
Simon Karlsson

Reputation: 4129

You could do something recursive like this:

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
        };
    }
}

Upvotes: 4

eran otzap
eran otzap

Reputation: 12533

You can do this :

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


    public class A
    {}

    public class B
    {}

Upvotes: 0

Related Questions