whereNoDuplicates method
Removes all duplicates, leaving only the distinct items.
Optionally, you can provide an by
function to compare the items.
If you pass removeNulls
as true, it will also remove the nulls
(it will check the item is null, before applying the by
function).
Note: This is different from List.distinct()
because removeDuplicates
is lazy (and you can use it with any Iterable, not just a List).
For example, it can be much more efficient when you are doing some extra
processing. Suppose you have a list with a million items, and you want
to remove duplicates and get the first 5:
// This will process 5 items: var newList = list.removeDuplicates().take(5).toList();
// This will process a million items: var newList = list.distinct().sublist(0, 5);
See also: distinct
and removeDuplicates
in FicListExtension.
Implementation
Iterable<T> whereNoDuplicates({
dynamic Function(T item)? by,
bool removeNulls = false,
}) sync* {
if (by != null) {
Set<dynamic> ids = <dynamic>{};
for (T item in this) {
if (removeNulls && item == null) continue;
dynamic id = by(item);
if (!ids.contains(id)) yield item;
ids.add(id);
}
} else {
Set<T> items = {};
for (T item in this) {
if (removeNulls && item == null) continue;
if (!items.contains(item)) yield item;
items.add(item);
}
}
}