Reputation: 3265
To simplify the problem, I suppose that I have a method with two boolean parameters getParamA and getParamB.
public JsonResult MyMethod(bool getParamA, bool getParamB)
Is There a way like a ternary operator or something to say if getParamA == true and getParamB == false for example, I create an anonymous object like this :
//this is an entityframework query
var result = entityContext.MyTable.Select(r=> new
{
paramA = r.paramA // because getParamA = true
// don't create paramB because getParamB is false
});
I know it is easy to implement this using two parameters (using if else condition) but things are getting complicated if we have more than 5 paramters (because you need to do all the testing)...
Upvotes: 1
Views: 79
Reputation: 157116
You can, but it isn't really efficient code. It makes your code a complete mess:
.Select( r => getParamA && getParamB
? (object)new { A = r.A, B = r.B }
: (getParamA ? new { A = r.A }
: (getParamB ? new { B = r.B }
: null
)
)
);
A better option might be the ExpandoObject
, which uses a dictionary internally to store its properties and values.
dynamic eo = new ExpandoObject();
if (getParamA)
{
eo.A = r.A;
}
if (getParamB)
{
eo.B = r.B;
}
Upvotes: 1