Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting different results filtering with foreach vs LINQ .Where()? [closed]

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?

like image 765
anita Avatar asked Nov 06 '22 22:11

anita


1 Answers

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.

like image 160
MemeDeveloper Avatar answered Nov 15 '22 09:11

MemeDeveloper