Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Data Transformation on Single Object

Tags:

c#

lambda

linq

I am trying to wondering if there is a way to transform a method result into a new object in a single line, as is possible when using a List, Linq, and Lambda expressions.

Example using lists:

List<int> ints = GetListOfInts();
List<anotherClass> = ints.Select(x => new anotherClass(){ memberVariable = x }).ToList();

Through this, I can map a list of type A to a list of type B.

I want to do this on a single object, not a list. Here is what I am intending:

// GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = (GetObjectA() x => new ObjectB(){ memberVariable = x });

This is just pseuodocode, and I know it will not compile or work. Is this type of transformation currently possible in C#?

I know I can use mappers, custom methods, etc., but I want to know if it is possible through lamba expressions as it is with lists.

like image 434
Jack Avatar asked May 10 '26 22:05

Jack


1 Answers

// GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = new[]{ GetObjectA() }.Select(x => new ObjectB(){ memberVariable = x }).First();

Not nice, but should work.

However, if it's really that specific code, you could just do

ObjectB objectB = new ObjectB(){ memberVariable = GetObjectA() };

If you want it encapsulated nicely, you could write something like this:

public static class ObjectExtensions
{
    public static TOutput Transform<TInput, TOutput>(this TInput input, Func<TInput, TOutput> transform)
    {
        return transform(input);
    }
}

and use it like that:

// GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = GetObjectA().Transform(x => new ObjectB(){ memberVariable = x });
like image 149
nvoigt Avatar answered May 12 '26 12:05

nvoigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!