How to search a list of Object by another list of items in dart

后端 未结 5 1352
一向
一向 2021-02-14 08:00

How to search a list of a class object with one of its property matching to any value in another list of strings

I am able to get filtering based on a single string , bu

相关标签:
5条回答
  • 2021-02-14 08:13
      List<SomeClass> list = list to search;
      List<String> matchingList = list of strings that you want to match against;
    
      list.where((item) => matchingList.contains(item.relevantProperty));
    

    If the number of items in list is large, you might want to do:

      List<SomeClass> list = list to search;
      List<String> matchingList = list of strings that you want to match against;
    
      final matchingSet = HashSet.from(matchingList);
    
      list.where((item) => matchingSet.contains(item.relevantProperty));
    

    Or else just always store the matching values as a hashset.

    0 讨论(0)
  • 2021-02-14 08:18

    In case if you want to check for a value in a list of objects . you can follow this :

     List rows = [
              {"ags": "01224", "name": "Test-1"},
              {"ags": "01224", "name": "Test-1"},
              {"ags": "22222", "name": "Test-2"},
            ];
        
        bool isDataExist(String value) {
        var data= rows.where((row) => (row["name"].contains(value)));
          if(data.length >=1)
         {
            return true;
         }
        else 
         {
            return false;
         }
        }   
    

    you can put your own array of objects on rows . replace your key with name . you can do your work based on true or false which is returned from the function isDataExist

    0 讨论(0)
  • 2021-02-14 08:19
     var one = [
        {'id': 1, 'name': 'jay'},
        {'id': 2, 'name': 'jay11'},
        {'id': 13, 'name': 'jay222'}
      ];
    
      int newValue = 13;
    
      print(one
          .where((oldValue) => newValue.toString() == (oldValue['id'].toString())));
    

    OUTPUT : ({id: 13, name: jay222})

    store output in any variable check if variable.isEmpty then new value is unique either

    var checkValue = one
          .where((oldValue) => newValue.toString() == (oldValue['id'].toString()))
          .isEmpty;
      if (checkValue) {
        print('Unique');
      } else {
        print('Not Unique');
      }
    

    OUTPUT : Not Unique

    0 讨论(0)
  • 2021-02-14 08:22

    You can simply use List.where() to filter a list

    final List<shop_cart.ShoppingCart> cartprd = snapshot.documents
          .where((f) => shop_cart.ShoppingCart.contains(f.data));
    
    0 讨论(0)
  • 2021-02-14 08:34

    As of today, you can't.

    (A side note : You can use .where, .singleWhere, .firstWhere. This site explains various list/array methods.)

    0 讨论(0)
提交回复
热议问题