Naor Hadar
Naor Hadar

Reputation: 577

Linq with regular array

I have an array of Item (A class I've made), and this is what I try to do:

foreach (Recipe recipe in recipes)
{
    if (recipe.All(i =>
    {
        Item item = inventory.Inventory.FirstOrDefault(x => x.ID == i.ID);
        return (item == null) ? false : (item.Amount >= i.Amount);
    }))
        ableToCraft.Add(recipe);
}

thanks for this question.

The problem is, where I run through the inventory with x (x => x.ID == i.ID), I come across x begin null because the cell the x try to point to from the array is null as well.

How can I fix that problem and make the program skip when they come across a null cell in the array?/

Upvotes: 0

Views: 92

Answers (3)

Dominic Zukiewicz
Dominic Zukiewicz

Reputation: 8444

Bundling it all into that foreach is a little ... confusing.

For maintenance, I'd use a Func<bool, Recipe> to make it easier to maintain.

Func<Recipe, bool> pricesAreCorrectForItem = (recipe) =>
     {
          var validInventoryItems = inventory.Inventory.Where(x=>x!=null);
          var item = validInventoryItems.FirstOrDefault(x=>x.ID == recipe.ID);
          return item == null ? false : (item.Amount >= recipe.Amount);
     };

foreach(Recipe recipe in recipes)
{
    if(recipe.All(pricesAreCorrectForItem))
        ableToCraft.Add(recipe);
}

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You could check for null first:

inventory.Inventory.FirstOrDefault(x => x != null && x.ID == i.ID);

Or filter the records before FirstOrDefault:

inventory.Inventory
.Where(x => x != null)
.FirstOrDefault(x => x.ID == i.ID);

Upvotes: 3

mnsr
mnsr

Reputation: 12437

try

(Recipe recipe in recipes)
                {
                    if (recipe.All(i =>
                    {
                        // this
                        Item item = inventory.Inventory.FirstOrDefault(x => x != null && x.ID == i.ID);
                        return (item == null) ? false : (item.Amount >= i.Amount);
                    }))
                        ableToCraft.Add(recipe);
                }

Upvotes: 2

Related Questions