Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get Data from List in List and compare with other list

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you very much for your help,
ReeN

>Solution :

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);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading