Simplify LINQ p = p.Type.ToUpper (). Equals ("S") && p.Mode.ToUpper (). Equals ("S") ..., n

3

How to simplify the LINQ expression?

p => p.Tipo.ToUpper().Equals("S") && p.Modo.ToUpper().Equals("S")...,n
    
asked by anonymous 05.10.2015 / 23:50

2 answers

2

You'll probably wonder if this is simpler. But it is, although bigger. And it is the right way, although I doubt if the right one 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 not do better than this.

If you prefer the "wrong" way:

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

Otherwise, if the condition is always the same, you can do a helper method that goes through all the required members and slightly reduce the code if you have too many conditions repeated. The list of members can be passed manually or can reduce more by using reflection. But in this case it will be confusing, rather perfunctory and if it is not to do with all members, would have to use annotations. That is, something so complicated that it would hardly justify use.

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

    
06.10.2015 / 00:28
0

Considering that easier to read and understand code is also simpler code, you could change the type of the Type and String Mode properties for enumerations. This would make the expression more explicit.

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

p => p.Tipo == Tipo.Simples && p.Modo == Modo.Serial
    
15.10.2015 / 16:11