Antoine C.
Antoine C.

Reputation: 3952

Foreach formatting with Resharper

While coding in C# (for a Windows Phone App, but I don't think it's relevant), I wrote a basic foreach statement, and then Resharper hit me with an autocorrection. And I don't understand at all the statement he created.

Here is the original code:

foreach (var val in settings.Values) 
{
    var valInfo = new ValueInfo(val.Value);
    FooMethod(val);
}  

Here is the Resharper code. It told me it was related to Linq, but from what I read in the MSDN I don't see the relationship with my code.

foreach (var val in from val in settings.Values 
         let valInfo = new ValueInfo(val.Value) 
         select val) 
{
    FooMethod(val);
}

Could someone explain to me why my statement is similar to Resharper's one ?

Upvotes: 1

Views: 207

Answers (2)

Vman
Vman

Reputation: 3136

Its just suggesting a linq query. It's not complicated but probably worth searching for a tutorial. Personally I'd just inline the valInfo, you might then find resharper suggests something:

likesettings.Values.ForEach(x=> FooMethod(new ValueInfo(x)));

Which personally I think is best interms of being concise but readable.

(might not be syntactically correct, but near enough)

Upvotes: 0

jdnew18
jdnew18

Reputation: 165

Well, it's just trying to condense the conditional of your foreach with the first line in your foreach statement (the let valInfo = new ValueInfo(val.Value line is setting your valInfo variable). It sure looks awful the way ReSharper has it, so, hey, feel free to ignore the suggestion and keep what you have.

But, if you're really feeling terribly curious...

The first part of ReSharper's foreach conditioner is the same as yours, that being

var val in

Then, if you ignore the line starting with let, you are left with the statement

var val in (from val in settings.Values select val)

where I have added parentheses for clarity. This is basically saying from thisColumn in someResultSet select thisColumn. If you are familiar with SQL, this will hopefully make some sense.

Again, the reason that the var val in (from val in settings.Values select val) nonsense got added was so that it could condense the conditional of your foreach with the first line in your foreach statement; it needed that there so it could set your valInfo variable with the let part of the Linq statement.

Upvotes: 1

Related Questions