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
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 to share