Gerald Degeneve
Gerald Degeneve

Reputation: 545

How to convert a nested data structure of TypeA to TypeB using LINQ

I have the Folowing Types:

class TypeA
{
    public string Name { get; set; }
    public object Value { get; set; } // Holds either a primitive DataType or a List<TypeA>
    public string IrrelevantInformation { get; set; }
}

class TypeB
{
    public string Name { get; set; }
    public object Value { get; set; } //Holds either a primitive DataType or a List<TypeB>
}

What I want is to convert a Hirarchical Structure of TypeA to TypeB.

I did it using a conventional recursive method:

private TypeB ConvertToTypeB(TypeA Input)
{
    return new TypeB() { Name = Input.Name, Value = ((Input.Value is List<TypeA>) ? ((List<TypeA>)Input.Value).Select(v=>ConvertToTypeB(v)).ToList() : Input.Value) };
}

My Question is: Can this be done without the ConvertToTypeB function using only one Linq query?

Upvotes: 1

Views: 108

Answers (1)

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

To convert hieractical structures the recursive call is required. There is no a way to exclude AtoB method.

Upvotes: 1

Related Questions