问题描述:

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?/

网友答案:

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);
网友答案:

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);
                }
网友答案:

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);
}
相关阅读:
Top