繁体   English   中英

Linq与常规数组

[英]Linq with regular array

我有一个Item数组(我做了一个类),这就是我要尝试做的:

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);
}

谢谢这个问题。

问题是,当我使用xx => x.ID == i.ID遍历清单时 ,遇到x开始为null,因为x尝试从数组指向的单元格也为null。

当它们遇到数组中的空单元格时,如何解决该问题并使程序跳过?/

您可以先检查null

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

或在FirstOrDefault之前过滤记录:

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

尝试

(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);
                }

将所有内容捆绑到foreach中有点令人困惑。

为了进行维护,我将使用Func<bool, Recipe>使其易于维护。

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM