François Beaune
François Beaune

Reputation: 4500

Transform an object to another, LINQ-style

LINQ allows to elegantly transform the collection returned by a method to a different collection, i.e.

var x = SomeMethod().Select(t => new { ... });

Now, is there a concise way in C# to transform the return value of a method without introducing an intermediary variable? Declaring and invoking a lambda seems to work but is quite ugly:

var x = new Func<T, object>(t => { return new { ... }; })(SomeMethod());

Am I missing something obvious or is this the best one can do with C# today?

Upvotes: 2

Views: 1225

Answers (2)

Fran&#231;ois Beaune
Fran&#231;ois Beaune

Reputation: 4500

I just figured that a generic extension method could fill the gap:

public static class TransformExtension
{
    public static T2 Transform<T1, T2>(this T1 t1, Func<T1, T2> transform)
    {
        return transform(t1);
    }
}

Sample usage:

public class A { };
public class B { };

void Foo()
{
    var a = new A();
    var b = a.Transform(x => new B());
}

Happy to hear why that's possibly a terrible idea.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

You can apply Select followed by Single to sequence of one item created from the result of calling SomeMethod, as follows:

var x = Enumerable.Repeat(SomeMethod(), 1).Select(r => new {...}).Single();

If you do it a lot, you can make a generic extension method for this:

static class MyExtensions {
    public static TRes Transform<TSrc,TRes>(this TSrc src, Func<TSrc,TRes> selector) {
        return selector(src);
    }
}

Now the syntax becomes very simple:

var res = SomeMethod().Transform(x => new { ... });

Upvotes: 1

Related Questions