1

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)...

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

13 Comments

Well, you are asking if it is possible, the answer is yes. Should you do it? No.
@MehdiSouregi ExpandoObject then?
Thanks, is it possible to implement it within the lambda expression above?
Wow, as the answerer said in your link, the implmentation is too overcomplicated :p so I am going to get all the columns and for my case it happens to be that all the parameters on the entry are the exact same parameters on the table. I can not use ExpandoObject for my case because it is not serializable, so maybe i am going to use an IDictionnary
@MehdiSouregi ExpandoObject is serializable to json (for example by JSON.NET). Besides - it already implements IDictionary<string, object>.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.