例如,假设您有一个苹果列表
List<String> apples = ['green', 'red','red', 'yellow']
并且您只想使用.removeWhere删除一个红苹果
apples.removeWhere((element => element == 'red));
然而,当我只想删除一个“red”的示例时,这会删除所有“red”的示例!有什么解决方案吗?
piah890a1#
您可以直接在列表中使用remove方法:
remove
List<String> apples = ['green', 'red','red', 'yellow']; apples.remove("red"); print(apples); // [green, red, yellow]
uajslkp62#
如果你想像使用removeWhere方法一样使用它,你可以使用这个扩展方法:将它添加到全局作用域(在类之外,将它放在任何需要的地方)
removeWhere
extension RemoveFirstWhereExt<T> on List<T> { void removeFirstWhere(bool Function(T) fn) { bool didFoundFirstMatch = false; for(int index = 0; index < length; index +=1) { T current = this[index]; if(fn(current) && !didFoundFirstMatch) { didFoundFirstMatch = true; remove(current); continue; } } } }
然后您可以这样使用它:
List<String> apples = ['green', 'red','red', 'yellow']; apples.removeFirstWhere((element) => element == 'red'); print(apples); // [green, red, yellow]
ua4mk5z43#
第三种解决方案是,如果你想删除List中的所有示例,使每个String只出现一次,你可以简单地将其设为Set:
List
String
Set
List<String> apples = ['green', 'red','red', 'yellow', 'green']; print(apples.toSet().toList()); // [green, red, yellow]
3条答案
按热度按时间piah890a1#
您可以直接在列表中使用
remove
方法:uajslkp62#
如果你想像使用
removeWhere
方法一样使用它,你可以使用这个扩展方法:将它添加到全局作用域(在类之外,将它放在任何需要的地方)
然后您可以这样使用它:
ua4mk5z43#
第三种解决方案是,如果你想删除
List
中的所有示例,使每个String
只出现一次,你可以简单地将其设为Set
: