我没有对象列表,例如
List<Product> products = [product1, product2, product1, product2, product1, product1]
如何从列表中获取唯一对象的列表及其编号?
import 'package:built_value/serializer.dart';
import 'package:built_value/built_value.dart';
part 'product.g.dart';
abstract class Product implements Built<Product, ProductBuilder>{
int get id;
String get title;
String get image;
double get price;
int get volume;
static Serializer<Product> get serializer => _$productSerializer;
Product._();
factory Product([updates(ProductBuilder b)]) = _$Product;
}
我想获取其他带有对象的列表:
class OrderPosition {
int id;
String title;
int count; // number of unique elements from list 'products'
}
例如:
List<OrderPosition> = [
OrderPosition(1, title1, 4),
OrderPosition(2, title2, 2)
]
答案 0 :(得分:3)
class Product {
Product(this.id); // for operator == to work properly
final int id; // make at least the id immutable
String title;
String image;
double price;
int volume;
bool operator ==(Object other) => identical(this, other) || (other as Product).id == id;
int get hashCode => id.hashCode;
}
var uniqueProducts = products.toSet().toList();
var result = <OrderPosition>[];
for(var i = 0; i < uniqueProducts.length; i++) {
result.add(
OrderPosition(i,
uniqueProducts[i].title,
products.where((e) => e == uniqueProducts[i]).length)));
}
答案 1 :(得分:2)
使用Set.putIfAbsent
的另一种方法是在一次迭代中收集信息:
var uniqueProductMap = Map<Product, OrderPosition>.identity();
for (var product in products) {
var position = uniqueProductMap.putIfAbsent(product,
() => OrderPosition(product.id, product.title, 0);
position.count++;
}
var uniqueProducts = uniqueProductMap.values.toList();
这使用identical
来确定哪些元素是唯一的。如果要改用相等,则仅用<Product, OrderPosition>{}
替换映射。如果要使用对象本身不支持的其他等效项,则可以使用:
var uniqueProductMap = LinkedHashMap<Product, OrderPosition>(
equals: (p1, p2) => p1.id == p2.id,
hashCode: (p) => p.id.hashCode);
(我完全支持将id
用作最终比较的建议)。
答案 2 :(得分:0)
Map<int, OrderPosition> _positionList = Map(); //map for orders (unique products and heir number)
List<Product> _orderList = [p1, p1, p2, p1, p3, p3, p2]; // list of products
..........
//
void addPosition(Product product) {
var uniqueProducts = _orderList.toSet().toList();
for(int i = 0; i < uniqueProducts.length; i++){
var value = OrderPosition(
uniqueProducts[i].title,
getCount(uniqueProducts[i].id));
_positionList[uniqueProducts[i].id] = value;
}
}