Home > Enterprise >  Get Data from List in List and compare with other list
Get Data from List in List and compare with other list

Time:10-30

I got following problem which I can't solved :(

Scenario: I have a list with Ingredients and I want to compare it with a recipes list which holds a list of ingredients depending on the recipes.

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

I am thankful for any help or idea :D!

Thank you very much for your help, ReeN

CodePudding user response:

I would start by changing the inventory to be a Set<String>. This will allow you to more efficiently check for subsets using the containsAll method.

You can then call where on the recipesList to get all of the elements where the inventory contains all of the itemNames for the given RecipeList object.

See implementation below:

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

CodePudding user response:

one of the approaches that you can take is to loop over the recipesList , hold every element in hand, then access the list in that element and loop over it then you can do whatever comparison you want with the inventory list

  • Related