I want to transform a foreach loop into LINQ. The code looks like this:
foreach (XmlNode localNode in localXmlNodeList)
{
var localKeyNode = localNode.SelectSingleNode(inputKeyName);
var localValueNode = localNode.SelectSingleNode(inputValueName);
if ((localKeyNode == null) || (localValueNode == null))
continue;
localReturn.Add(localKeyNode.InnerText, localValueNode.InnerText);
}
I wanted to use something like:
from X in Y
let varA = Y.A
let varB = Y.B
where method(varA, varB)
select varA, varB;
but I always end up using a foreach loop like:
foreach(var X in Y.Where(varA => something(varA.subA.microSubA, varB.subB.microSubB)))
{
somethingAgain(varA.subA.microSubA, varB.subB.microSubB)
}
where I wasn't able to introduce "let".
Can Somebody help me ?
You can use let
in a foreach
loop:
// Query modified slightly to make more sense...
foreach (var X in from X in Y
let varA = X.A
let varB = X.B
where method(varA, varB)
select new { varA, varB })
It's ugly, but it should still work - it's just an expression.
Or, better IMO, declare a separate query variable first:
var query = from X in Y
let varA = X.A
let varB = X.B
where method(varA, varB)
select new { varA, varB };
foreach (var X in query)
{
...
}
Of course, let
really just corresponds to another Select
to introduce the range variable - so you can express it in dot notation as well:
var query = Y.Select(X => new { X, varA = X.VarA })
.Select(p => new { p.X, p.varA, varB = p.X.VarB })
.Where(p => method(p.varA, p.varB))
.Select(p => new { p.varA, p.varB });
See more on this question at Stackoverflow