简体   繁体   中英

how to merge more than one list into only one list? dart

i have a

class shop {
int id;
String name;
List<Product> products;
}

class Product {
int id;
String productName;
}

where each shop has his own products, how to merge all shops products in one list how to create a List of all products

You can simply merge Lists with + operator:

List<Product> list1 = ...;
List<Product> list2 = ...;
List<Product> list3 = ...;

List<Product> mergedList = list1 + list2 + list3;

Also, Dart 2.3 and higher supports spread operator, which can be used as follows:

List<Product> mergedList2 = [...list1, ...list2, ...list3];

For dynamic number of shops you can use basic forEach:

List<Shop> shops = ...;

List<Product> mergedList = List();

shops.forEach((shop) => mergedList.addAll(shop.products));

You can merge lists using + or the spread operator

Using the Addition Operator:

List<shop> shops = [shop1, shop2];
List<Product> products = shop1.products + shop2.products;

Using Spread Operator:

List<Product> products = [...shop1.products, ...shop2.products];

Edit

You would need to do it like this:

List<shop> shops = [shop1, shop2,...];
List<Product> mergedProducts = []
for(int i = 0; i < shops.length; i++){
    mergedProducts = mergedProducts + shops[i].products;
}

I think you're looking for the fold function. You can do it in 1 line.

List<Shop> shops = [shop1, shop2, shop3];

List<Product> allProducts = shops.fold<List<Product>>([], (productList, shop) => productList..addAll(shop.products));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM