Simplify LINQ p => p.Tipo.Toupper(). Equals("S") && p.Modo.Toupper(). Equals("S")...,n

Asked

Viewed 94 times

3

How to simplify LINQ expression?

p => p.Tipo.ToUpper().Equals("S") && p.Modo.ToUpper().Equals("S")...,n

2 answers

2


You’ll probably wonder if this is simpler. But it is, though it’s bigger. And it’s the right way, although I doubt whether the right way should be used.

p => p.Tipo.Equals("S", StringComparison.InvariantCultureIgnoreCase) &&
     p.Modo.Equals("S", StringComparison.InvariantCultureIgnoreCase)...,n

Unless you have a more specific context, you can’t do better than this.

If you prefer the "wrong way":

p => p.Tipo.ToUpper() == "S" && p.Modo.ToUpper() == "S"...,n

I put in the Github for future reference.

Otherwise, if the condition is always the same, you can make an auxiliary method that goes through all the necessary members and reduce the code a little, if you have many repeated conditions. The membership list can be passed manually or it can reduce more using reflection. But in this case it will be confused, not performative and if not to do with all the members, would have to use notes. That is, something so complicated that it would hardly justify the use.

And here we are talking about making code reduced and not simplified.

0

Whereas easier to read and understand code is also simpler code, you could change the type of the Type and String mode properties for enumerations. Thus the intention of the expression would be much more explicit.

Example - considering that only by the value’S' it is not possible to know what each property means, so I define random enumerations:

p => p.Tipo == Tipo.Simples && p.Modo == Modo.Serial
  • Unless I didn’t understand, you shouldn’t do this. Enum is to compose mechanisms and not business rules: http://answall.com/q/21997/101

  • @bigown - there is not enough information in the question to define the semantics of these properties and thus, conclude what you suggest....

  • Then your answer is wrong?

  • My answer is an example, where I freely interpreted what the string’S' could mean for the Type property and for the Mode property. My reply tried to show that it is much clearer, for example, define enumerations with more explicit members' names to make semantics clear and make it easier to read the code - easy to read code is also simpler code.

  • Meaning, according to yourself, you answered what you wanted and not what you were asked? There she is wrong, should be a comment, because it does not solve the real problem. And I had already noticed this.

  • If you think so, signal to the moderators, please, and stop criticizing different views simply because you don’t agree with them.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.