簡體   English   中英

LINQ 查詢比較兩個列表與子列表

[英]LINQ Query comparing two lists with sublist

我正在制作一個具有制作系統的游戲。 我正在嘗試獲取食譜列表,但只顯示玩家在他們的庫存中擁有足夠多的食譜。 我很難弄清楚這個查詢。 這是我的精簡課程:

public class GameItem
{
    public string itemName;
    public int quantityHeld;
}

public class GameItemRecipe : GameItem
{
    public GameItemIngredient[] giiIngredients;
}

public class GameItemIngredient : GameItem
{        
    public int quantityNeeded;
}

所以我有一個 GameItems 列表; 那是玩家的物品欄。 然后我有一個玩家知道的食譜的單獨列表。 食譜有一個制作它所需成分的子列表。 所以我想獲取庫存中有足夠物品的食譜列表。 任何幫助表示贊賞。

var recipes = new List<GameItemRecipe>();
var inventory = new List<GameItem>();

var possibleRecipes = recipes.Where(rec => r.giiIngredients.
                          All(i => ing.quantityNeeded <= inventory.
                          FirstOrDefault(gi => gi.itemName== ing.itemName)?.quantityHeld));

此查詢獲取您的所有食譜,其中對於所有成分,數量需求字段小於或等於游戲物品清單中具有相同物品名稱的游戲物品的持有數量字段。

所以你有一個Player ,這個 Player 有一個Inventory ,它是一系列GameItems 其中一些 GameItems 可能是GameItemIngredients 您沒有指定 Inventory 中的所有 GameItems 都是 GameItemIngredients,因此 Inventory 中的某些 GameItems 可能不是 GameItemIngredients。

此外,玩家知道GameItemRecipes的序列。 要制作其中一種配方,玩家需要配方中提到的GameItemIngredients

玩家需要知道他可以制作哪些食譜。 換句話說:對於哪些食譜,玩家有足夠的成分。

IEnumerable<GameItem> inventory = ...
IEnumerable<GameItemRecipe> recipes = ...

從中您可以提取玩家在他的庫存中擁有的所有成分:

IEnumerable<GameItemIngredient> ingredients = inventory.OfType<GameItemRecipe>();

要求:給我玩家可以制作的所有食譜; 這些都是玩家擁有所有成分的食譜。

每個 GameItemIngredient 都有一個屬性RequiredQuantity 我假設每個食譜都會有制作食譜所需的 GameItemIngredients 的唯一名稱。

簡單地說:如果你需要兩個土豆來制作食譜“土豆泥”,那么食譜的成分列表將只包含一種名稱為“土豆”的成分。 該成分的數量為 2。因此,您的食譜中不會出現兩次土豆成分。

此外,我假設您不會在食譜中進行子分類:如果您的食譜需要“蘋果”,並且您的庫存中有“史密斯奶奶”,那么唉,您無法制作食譜,甚至雖然“Granny Smith”是“Apple”。

如果配方的所有成分都在庫存的成分中並且QuantityNeeded <= QuantityHeld ,則可以制作配方。

因此,對於每個配方,我們都需要檢查成分是否在庫存中。 為了提高效率,我們將制作庫存中成分的字典。 Key是成分的ItemName 值是QuantityHeld

var ingredientQuantities = ingredients.ToDictionary(
    ingredient => ingredient.ItemName,
    ingredient => ingredient.QuantityHeld);

如果“Apple”與“apple”的成分相同,請考慮使用 EqualityComparer

配方中每種成分的 ItemName 應該是 Dictionary 中的一個鍵,並且 QuantityNeeded <= QuantityHeld (= Dictionary 中的值)

var recipesThatCanBeMade = recipes
   .Where(recipe => !recipe.Ingredients.All(ingredient =>
       ingredientQuantities.TryGetValue(ingredient.ItemName, out int quantityHeld)
       && ingredient.QuantityNeeded <= quantityHeld)

換句話說:從食譜序列中的每個食譜中,只保留那些食譜

  • 所有成分都有一個 ItemName ,它是字典中的一個鍵,
  • 並且有一個 QuantityNeeded,它小於或等於 Dictionary 中對應值的 QuantityHeld。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM