我遇到了以下我無法解決的問題:(
場景:我有一個包含成分的串列,我想將它與一個食譜串列進行比較,該串列包含一個取決于食譜的成分串列。
List<RecipeList> recipesList = [
RecipeList(recipeName: "Cake", itemNames: ["banana", "appel"]),
RecipeList(recipeName: "Soup", itemNames: ["potatato", "egg"]),
RecipeList(recipeName: "Sandwich", itemNames: ["Toast", "Sausage", "Ketchup"]),
RecipeList(recipeName: "Pizza", itemNames: ["Tomato", "Mushroom"]),
];
List inventory = ["coke", "egg", "banana", "apple"];
class RecipeList {
String? recipeName;
List<String>? itemNames;
RecipeList({this.recipeName, this.itemNames});
}
我感謝任何幫助或想法:D!
非常感謝你的幫助,ReeN
uj5u.com熱心網友回復:
我首先將庫存更改為Set<String>. containsAll這將允許您使用該方法更有效地檢查子集。
where然后,您可以呼叫recipesList以獲取inventory包含itemNames給定RecipeList物件的所有元素的所有元素。
請參閱下面的實作:
List<RecipeList> recipesList = [
// fixed misspelling of "apple"
RecipeList(recipeName: "Cake", itemNames: ["banana", "apple"]),
RecipeList(recipeName: "Soup", itemNames: ["potatato", "egg"]),
RecipeList(
recipeName: "Sandwich", itemNames: ["Toast", "Sausage", "Ketchup"]),
RecipeList(recipeName: "Pizza", itemNames: ["Tomato", "Mushroom"]),
];
// change inventory to a Set<String>
Set<String> inventory = {"coke", "egg", "banana", "apple"};
class RecipeList {
String? recipeName;
List<String>? itemNames;
RecipeList({this.recipeName, this.itemNames});
}
void main() {
var results =
recipesList.where((v) => inventory.containsAll(v.itemNames ?? []));
for (var result in results) {
print(result.recipeName);
}
}
uj5u.com熱心網友回復:
您可以采取的一種方法是遍歷recipesList ,將每個元素放在手邊,然后訪問該元素中的串列并遍歷它,然后您可以對inventory串列進行任何您想要的比較
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523381.html
標籤:扑列表镖
