I'm facing a problem that I need to construct one object from multiple types and return to the front end, here is what I want(In C#).
The shape that front end wants is like this
{
...
"props" : // this is the place I need to fill-up.
...
}
For the controller, it's a custom response.
public IActionResult Index()
{
return JohnDoe.Render();
}
Behind the scenes, Render
is going to get some data from two places.
public object Foo()
{
return string, int, IEnumerable, instance, etc;
}
public object Bar()
{
return string, int, IEnumerable, instance, etc;
}
I know the return
statement is not valid, what I mean is that those are all the possibilities.
And here is eventually what I want.
public object Combine()
{
var foo = Foo();
var bar = Bar();
return foo + bar;
}
Again the return
statement is not valid, I want to have a final object
that contains both of them. It can be Dictionary<string, object>
or anonymous object new {}
, or something else does not matter as long as one object has both of them.
Obviously what I have here is not possible to achieve it. Here are the two options I came up with.
- Just use a wrapper to wrap them, Here is what I do.
public object Combine()
{
var foo = Foo();
var bar = Bar();
return new { foo, bar };
}
I know I can have a Type
rather than an anonymous object, the thing is that this will introduce two keys foo
and bar
, which I do not want to if possible.
- Make the
foo
andbar
only returninstance
. NOstring
,int
,Array
,IEnumerable
etc. If I do it in this way, things get a little bit easier. All I need to do is looping through theproperties
getting thevalues
and map to eithernew {}
orDictionary<string, object>
. This way I do not need to introduce new keys.
Update : so basically I want to avoid introducing new keys if I can, as I just want to return the original without a wrapper. That's why I came up with option 2, only instance
is allowed. Let me know your thoughts, please.