How to get Resharper to convert back to a foreach loop - linq

Resharper 5 can convert my foreachloops to Linq queries. Which I like. But linq is way way way harder to debug than a foreachloop.
When I convert my foreach statement to a linq query, I don't see any option to go back the other way.
Does any one know how to do this? Is it even possible?

We are working on LINQ2Foreach (and some other) functionality for ReSharper vNext

I do not believe this is possible. Certainly, it's not listed in the examples of Quick Fixes, where loop-to-LINQ-expression is shown.
What you should be able to do is use the Context Action 'Convert LINQ to methods chain' to go from the 'fluent' style to the 'methods' style, and then selectively use 'Introduce variable' to pull the expression to pieces.

Related

Entity Framework Syntax for Beginners

Can anyone please help me with a general Entity Framework question? I'm a newbie and trying to teach myself from reading and trial & error. However, I'm getting REALLY confused on all the syntax and terminology. And the more I google, the more confused I get!
What in the world are those little arrows (=>) used in the syntax? And I'm not even sure what the name of the syntax is...is it Entity Framework syntax? Linq to method syntax? Linq to Entity syntax?
Why does it seem like you can use random letters when using that syntax? the "f" below seems interchangeable with any alphabet letter since Intellisense gives me options no matter what letter I type. So what is that letter supposed to stand for anyway? There seems to be no declaration for it.
var query = fruits.SelectMany(f => f.Split(' '));
Is it better to use the syntax with the little arrows or to use the "psuedo SQL" that I keep seeing, like below. This seems a little easier to understand, but is this considered not the Real Entity Framework Way?
var query = from f in fruits from word in f.Split(' ') select word;
And, for any of them - is there any documentation out there ANYWHERE?? I've been scouring the internet for tutorials, articles, anything, but all that comes back are small sample queries varying with the little arrows or that psuedo SQL, with no explanations beyond "here's how to do a select:"
I would much appreciate any guidance or assistance. I think if I can just find out where to start, then I can build myself from there. Thanks!
There is no real entity way, there is LINQ and there is LINQ extension methods which is my opinion is much cleaner to the eyes. Also you can use LINQ not just with EE.
Language Integrated Query
LINQ extends the language by the addition of query expressions, which are akin to SQL statements, and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources. Other uses, which utilize query expressions as a general framework for readably composing arbitrary computations, include the construction of event handlers2 or monadic parsers.3
1 It is called lambda expression and it is basically an anonymous method.
Exploring Lambda Expression in C#
2 You can use anything you want, word, or letters, anything that is a valid name for a parameter, because that is a parameter
3 I find the LINQ extension methods to be cleaner, and to be honest the last I want to see is SQL like statements laying in the code.
4 A good start can be found here
101 LINQ SAMPLES
The arrow is called a Lambda operator, and it's used to create Lambda expressions. This has nothing to do with EF, or Linq or anything else. It's a feature of C#. EF and Linq just use this feature a lot because it's very useful for writing queries.
Marco has given links to the relevant documentation.
Linq is a library of extension methods that primarily operate on types like IEnumerable and IQueryable interfaces, and give you a lot of power to work with collections of various types. You can write Linq queries either in two formats, so called Method syntax and Query Syntax. They are functionally identical, but their usage is generally a matter of personal preference which one you use (although many of us use both, depending on the context it's used in.. one or the other is easier to use).

How do you build your LINQ queries?

It seems there are two ways to build queries -- either using query expressions:
IEnumerable<Customer> result =
from customer in customers
where customer.FirstName == "Donna"
select customer;
or using extension methods:
IEnumerable<Customer> result =
customers.Where(customer => customer.FirstName == "Donna");
Which do you use and why? Which do you think will be more popular in the long-run?
Only a limited number of operations are available in the expression syntax, for example, Take() or First() are only available using extension methods.
I personally prefer expression if all the required operations are available, if not then i fall back to extension methods as I find them easier to read than lambdas.
take a look at this answer,
Linq Extension methods vs Linq syntax
I use the method syntax (almost) exclusively, because the query syntax has more limitations. For maintainability reasons, I find it preferable to use the method syntax right away, rather than maybe converting it later, or using a mix of both syntaxes.
It might be a little harder to read at first, but once you get used to it, it works fairly natural.
I only use the method syntax. This is because I find it a lot faster to write, and I write a ton of linq. I also like it because it is more terse. If working on a team, its probably best to come to a concensus as to which is the preferred style, as mixing the two styles is hard to read.
Microsoft recommends the query syntax. "In general, we recommend query syntax because it is usually simpler and more readable". http://msdn.microsoft.com/en-us/library/bb397947.aspx
It depends on which you and your team find more readable, and I would choose this on a case by case basis. There are some queries that read better in syntax form and there are some that read better in method form. And of course, there is that broad middle ground where you can't say one way or the other, or some prefer it this way and others that way.
Keep in mind that you can mix both forms together where it might make it more readable.
I see no reason to suspect that either form will dissappear in the future.

Is there an application for displaying some kind of query plan for a Linq to object query?

I'm looking for an application to display what a linq expression would do, in particular regarding the usage of multiple access to the same list in a query.
Better yet, the tool would tell if the linq query is good.
I used the expression tree visualizer in the past to at least help decode what is inside of an expression tree. It aids in figureing out the parts of the tree and how gives each part is related.
Well, to begin with, I could easily foresee a tool that would pick a query apart and detect that the Where-clause is the standard runtime implementation, and thus not examine that method, but "know" what the execution plan for that method would be, and could thus piece together a plan for the whole query.
Right up until the point where you introduce a custom Linq provider, where the only way to figure out what it will be doing would be to read the code.
So I daresay there is no such tool, and making one would be very hard.
Would be fun to try though, at least for standard classes, would be a handy debugging visualizer for Visual Studio.
What about making the tool yourself?! ;)
Take a look at Expression trees, I believe they might be useful

A DSL for Linq Queries - looking for ideas

I am currently using a CMS which uses an ORM with its own bespoke query language (i.e. with select/where/orderby like statements). I refer to this mini-language as a DSL, but I might have the terminology wrong.
We are writing controls for this CMS, but I would prefer not to couple the controls to the CMS, because we have some doubts about whether we want to continue with this CMS in the longer term.
We can decouple our controls from the CMS fairly easily, by using our own DAL/abstraction layer or what not.
Then I remembered that on most of the CMS controls, they provide a property (which is design-time editable) where users can type in a query to control what gets populated in the data source. Nice feature - the question is how can I abstract this feature?
It then occurred to me that maybe a DSL framework existed out there that could provide me with a simple query language that could be turned into a LINQ expression at runtime. Thus decoupling me from the CMS' query DSL.
Does such a thing exist? Am I wasting my time? (probably the latter)
Thanks
this isn't going to answer your question fully, but there is an extension for LINQ that allows you to specify predicates for LINQ queries as strings called Dynamic LINQ, so if you want to store the conditions in some string-based format, you could probably build your language on top of this. You'd still need to find a way to represent different clauses (where/orderby/etc.) but for the predicates passed as arguments to these, you could use Dynamic LINQ.
Note that Dynamic LINQ allows you to parse the string, but AFAIK doesn't have any way to turn existing Expression tree into that string... so there would be some work needed to do that.
(but I'm not sure if I fully understand the question, so maybe I'm totally of :-))

How to debug a LINQ Statement

I have a Linq to objects statement
var confirm = from l in lines.Lines
where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)
select l;
The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over?
EDIT When I said I know for a fact that there are no null objects it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really'
LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool
Yes it is indeed possible to pause execution midway through a linq query.
Convert your linq to query style using lambda expressions and insert a Select statement that returns itself somewhere after the point in the linq that you want to debug. Some sample code will make it clearer -
var query = dataset.Tables[0].AsEnumerable()
.Where (i=> i.Field<string>("Project").Contains("070932.01"))
// .Select(i =>
// {return i;}
// )
.Select (i=>i.Field<string>("City"));
Then uncomment the commented lines. Make sure the {return i;} is on its own line and insert a debug point there. You can put this select at any point in your long, complicated linq query.
I'm not sure if it's possible to debug from VS, but I find LINQPad to be quite useful. It'll let you dump the results of each part of the LINQ query.
You should be able to set a breakpoint on the expression in the where clause of your LINQ statement.
In this example, put the cursor anywhere in the following section of code:
(l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)
Then press F9 or use the menu or context menu to add the breakpoint.
When set correctly, only the above code should have the breakpoint formatting in the editor rather than the entire LINQ statement. You can also look in the breakpoints window to see.
If you've set it correctly, you will stop each time at the function that implements the above part of the query.
I wrote a comprehensive article addressing this very question published on Simple-Talk.com (LINQ Secrets Revealed: Chaining and Debugging) back in 2010:
I talk about LINQPad (as mentioned earlier by OwenP) as a great tool external to Visual Studio. Pay particular attention to its extraordinary Dump() method. You can inject this at one or more points in a LINQ chain to see your data visualized in an amazingly clean and clear fashion. Though very useful, LINQPad is external to Visual Studio. So I also present several techniques available for use within Visual Studio because sometimes it is just not practical to migrate a chunk of code over to LINQPad:
(1) Inject calls to the Dump() extension method I present in my article to allow logging. I started with Bart De Smet's Watch() method in his informative article LINQ to Objects – Debugging and added some labeling and colorization to enhance the visualization, though still it pales in comparison to LINQPad's Dump output.
(2) Bring LINQPad's visualization right into Visual Studio with Robert Ivanc's LINQPad Visualizer add-in. Not sure if it was through my prodding :-), but the couple inconveniences present when I was writing my article have now all been admirably addressed in the latest release. It has full VS2010 support and lets you examine any object you like when debugging.
(3) Embed nop statements in the middle of your LINQ chain so you can set breakpoints, as described earlier by Amazing Pete.
2016.12.01 Update
And I just wrote the sequel to the above article, titled simply LINQ Debugging and Visualization, which reveals that true LINQ debugging capability has finally arrived in Visual Studio 2015 with the about-to-be-released new feature in OzCode. #Dror's answer to this question shows a tiny glimpse of it, but I encourage you to read my new article for an in-depth "how to". (And I do not work for OzCode.:-)
[Disclaimer: I work at OzCode]
The problem with LINQ is that it's hard to impossible to debug - even when dealing simple queries a developer is forced to refactor his/her query to a bunch of foreach loops, or use logging.
LINQ debugging is supported in a soon-to-be-released version of OzCode (currently available as an Early Access Preview) and it helps developers drill into their LINQ code as well and pinpoint those hard to catch exceptions inside queries
This is what your query would look like in OzCode:
It is possible to step inside the LINQ expression without setting any temporary breakpoints. You need to step into the function which evaluates the LINQ expression, e.g.:
var confirm = from l in lines.Lines
where (l.LineNumber == startline.LineNumber)
|| (l.LineNumber == endline.LineNumber)
select l;
confirm.ToArray(); // Press F11 ("Step into") when you reach this statement
foreach(var o in q) // Press F11 when "in" keyword is highlighted as "next statement"
// ...
Check the exception stack trace and see the last bit of your code that executed.
From the looks of the error I would suggest you take a look at line.Lines and make sure its enumerator is implemented properly. I think it's returning a null when it shouldn't.
Oh and just make sure the line and line.Lines objects aren't null or returning nulls as well.
While it isn't a way of debugging, I'd suggest using the following:
using (var db = new AppContext())
{
db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
// Rest of code
}
You can then check the output window when debugging to see the SQL generated from your LINQ query.
To step through the LINQ statement just put a breakpoint on linq statement and then when it starts to debug that line then
Right click on it
click on Run To Cursor option
It will start to execute code line by line as we do normally.

Resources