LINQ versus harvest

I hardly use the "yield" operator (I don't hate it :)). I prefer to use LINQ if possible. Anyway, I was looking for some kind of post (you can find the link below) 10 minutes ago, read it, and some idea visited my brain :)

rewrite-this-foreach-yield-to-a-linq-yield

Idea: It’s probably not very good that I do not use “profitability”. It probably has better performance than LINQ or some other advantage.

So I have the following question: which code is more “correct” (output or LINQ) in the example above (in the general case)?

PS I'm interested in cases where we have the opportunity to use LINQ instead of "yield".

+4
source share
3 answers

I think it is more clear to use LINQ in this case personally. It works at a higher level than "this method is called, give this result" - it describes the general results.

Iterator blocks are very useful for implementing LINQ, although they are either existing statements or adding your own. It is worth knowing about them, but I would not worry that you use them a little - this is not a sign of bad code or something like that.

+8
source
public static IEnumerable<Color> GetThemColors(){ GetThePrimaryIds().Select(id=>yield return GetColorById(id)); GetTheOtherIds().Select(id=>yield return GetOtherColorsById(id)); } 

This code does not work. The choice is lazy and these collections are not listed.

+1
source

Ignoring the way in which Linq can be processed by other query providers (for example, for a database), in the example you are referring to, we have two different approaches:

  • First you get everything from the first listing, and then release everything from the second.
  • Call the Enumerable.Concat method.

Well, what is Enumerable.Concat ? Since we ignore cases like Linq2SQL (which will most likely turn concat into UNION ALL ), what we care about here is the implementation of Linq2Objects.

Now you have more than one way to bypass the concat, but the Mono source (for example) finishes calling the check, and then:

 static IEnumerable<TSource> CreateConcatIterator<TSource> (IEnumerable<TSource> first, IEnumerable<TSource> second) { foreach (TSource element in first) yield return element; foreach (TSource element in second) yield return element; } 

In other words, the LINQ approach is a yield approach.

Or, if not, it could be something very similar. We could (if we liked printing more) implement it as an IEnumerator<TSource> implementation construct, but yield saves us the hassle.

In general, LINQ is a set of handy tools that work well together. When it is a tool that works well, use them. When another tool works better, use it. When the LINQ-like tool is nice, but it is not included in what you have, write it yourself (just like we could do all the Linq2Objects stuff before Linq, which was not for us in .NET2.0) .

+1
source

All Articles