Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform these operations for the "List": map, group, lookup, aggregate, sort?

Tags:

dart

I have the List of categories and their products and I want to perform these operations:

  • Map
  • Group
  • Lookup
  • Query aggregate functions
  • Sorting by multiple fields

How this can be done in Dart?

void main() {
  var books = new Category(0, "Books");
  var magazines = new Category(1, "Magazines");
  var categories = [books, magazines];
  var products = [
    new Product(0, "Dr. Dobb's", magazines),
    new Product(1, "PC Magazine", magazines),
    new Product(2, "Macworld", magazines),
    new Product(3, "Introduction To Expert Systems", books),
    new Product(4, "Compilers: Principles, Techniques, and Tools", books),
  ];      

  // How to map product list by id?

  // How to group product list by category?

  // How to create lookup for product list by category?

  // How to query aggregate functions?

  // How to sort product list by category name and product name?      
}

class Category {
  int id;
  String name;

  Category(this.id, this.name);

  operator ==(other) {
    if(other is Category) {
      return id == other.id;
    }

    return false;
  }

  String toString() => name;
}

class Product {
  int id;
  String name;
  Category category;

  Product(this.id, this.name, this.category);

  operator ==(other) {
    if(other is Product) {
      return id == other.id;
    }

    return false;
  }

  String toString() => name;
}

These lists are similar to records in data tables.

like image 911
mezoni Avatar asked Dec 16 '13 11:12

mezoni


1 Answers

Mapping can be done with the .map method, like so: products.map((product) => product.id) This will return a list of the product ids.

Grouping would be done with the fold method. For example, if you wanted to group products by category:

product.fold<Map<String, List<Product>>>({}, (productMap, currentProduct) {
  if (productMap[currentProduct.category.name] == null) {
    productMap[currentProduct.category.name] = [];
  }
  productMap[currentProduct.category.name].add(currentProduct);
  return productMap;
});

Lookup is done with .firstWhere. For example: products.firstWhere((product) => product.category.name === 'books');

like image 55
Spencer Stolworthy Avatar answered Sep 23 '22 17:09

Spencer Stolworthy