我的对象列表,例如
List<Product> products = [product1, product2, product1, product2, product1, product1]
Run Code Online (Sandbox Code Playgroud)
如何从列表中获取带有编号的唯一对象列表?
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;
}
Run Code Online (Sandbox Code Playgroud)
我想用对象获取其他列表:
class OrderPosition {
int id;
String title;
int count; // number of unique elements from list 'products'
}
Run Code Online (Sandbox Code Playgroud)
例如:
List<OrderPosition> = [
OrderPosition(1, title1, 4),
OrderPosition(2, title2, 2)
]
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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)));
}
Run Code Online (Sandbox Code Playgroud)