I seem to be getting different results when filtering.
I expect the same result from these two pieces of code :
Sitecore.Data.Items.Item firstGuess = Sitecore.Context.Database.GetItem(mediaPath);
var matches = new List<Item>();
//Method A
foreach (var child in firstGuess.Parent.Children.InnerChildren)
{
if (child.DisplayName == firstGuess.DisplayName)
{
matches.Add(child);
}
}
//Matches.count = 2
//Method B
var matches2 = firstGuess.Parent.Children.InnerChildren.Where(i => i.DisplayName == firstGuess.DisplayName);
//matches2.any = false
I am trying to find items which have the same name as my firstGuess
.
Method A works as expected, but B seems to give me a odd result in that !matches2.any()
returns false
, when I would expect true
.
Tested with both .Where
and .Select
Why do are these seemingly equivalent methods give me different results?
Hard to say without more info, but you could try this, i.e. ensure you are not suffering from mutation of firstGuess in the foreach loop. Get the result twice.
var firstGuess = Sitecore.Context.Database.GetItem(mediaPath);
var firstGuess2 = Sitecore.Context.Database.GetItem(mediaPath);
var matches = new List<Item>();
//Method A
foreach (var child in firstGuess.Parent.Children.InnerChildren)
{
if (child.DisplayName == firstGuess.DisplayName)
{
matches.Add(child);
}
} //Matches.count = 2
//Method B
var matches2 = firstGuess2.Parent.Children.InnerChildren.Where(i => i.DisplayName == firstGuess.DisplayName).ToList();
And also ToList() the where to ensure the IQueryable<> is definitely executed.
Generally - if you find something unexpected in code like this - replace var
with the explicit types - this may well make the oddity apparent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With