0

I have two Lists

List 1 contains an object. One of the aspects of that object is a person ID [1,2,3,4,5] and List 2 contains the person ID's whom match a criteria [1,3,5]

I need to filter list 1 to only show the objects where the criteria is met.

Something like:

 var sortedList = list1
          .where((item) => item.personID == "Any of the ids contained within list2)
          .toList();

Therefore sortedList = the objects for id 1,3,5

1 Answer 1

1

Short answer

Iterable<Item> filteredList = list.where((element) {
    return list2
        .map((elem) => elem.personId)
        .toList()
        .contains(element.personId);
  });

You may look into this Dart Playground. Dartpad

Full Script

class Item {
  int personId;
  Item({this.personId});

  String toString() {
    return "$personId";
  }
}

List<Item> list = [
  Item(personId: 1),
  Item(personId: 2),
  Item(personId: 3),
  Item(personId: 4),
  Item(personId: 5),
];

List<Item> list2 = [
  Item(personId: 1),
  Item(personId: 3),
  Item(personId: 5),
];

void runFunction() {
  Iterable<Item> filteredList = list.where((element) {
    return list2
        .map((elem) => elem.personId)
        .toList()
        .contains(element.personId);
  });
  List<Item> result = filteredList.toList();
  print(result);
}

main() {
  runFunction();
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.