I have a piece of code for some verification logic, which in a generalized form looks like this:
private bool AllItemsAreSatisfactoryV1(IEnumerable<Source> collection) { foreach(var foo in collection) { Target target = SomeFancyLookup(foo); if (!target.Satisfactory) { return false; } } return true; }
It works, is pretty easy to understand, and it has optimization. This, however, is rather verbose. The main purpose of this question is what is considered readable and good style. I am also interested in performance; I strongly believe that premature (optimization, pessimization) is the root of all evil and is trying to avoid microoptimization, as well as introduce bottlenecks.
I am new to LINQ, so I would like to get some comments on the two alternative versions that I came up with, as well as any other suggestions. readability.
private bool AllItemsAreSatisfactoryV2(IEnumerable<Source> collection) { return null == (from foo in collection where !(SomeFancyLookup(foo).Satisfactory) select foo).First(); } private bool AllItemsAreSatisfactoryV3(IEnumerable<Source> collection) { return !collection.Any(foo => !SomeFancyLookup(foo).Satisfactory); }
I don't think V2 offers much more than V1 in terms of readability, even if it is shorter. I find V3 clear and concise, but I don't like the Method().Property part too much; Of course, I could turn the lambda into a full delegate, but then it loses its one-line elegance.
I would like the comments to be:
- Style is so subjective, but what do you think is readable?
- Is a performance a definite no-no? As far as I understand, all three methods should be early.
- Is debugging all you need to consider?
- Alternatives - everything goes.
Thanks in advance:)
performance c # coding-style foreach linq-to-objects
snemarch
source share