简体   繁体   English

Dart 中的 List take() 与 getRange() 有什么区别

[英]What's the difference between List take() vs. getRange() in Dart

I want the first n elements of some List .我想要一些List的前n 个元素。 From what I can tell, I have two options: take(n) and getRange(0, n) .据我所知,我有两个选择: take(n)getRange(0, n)

  1. What's the difference between them?它们之间有什么区别?
  2. When would I use one over the other (assuming I always want the first n elements)?我什么时候会使用一个而不是另一个(假设我总是想要前n 个元素)?

The most obvious difference is that take() can only use elements at the beginning, you can combine it with skip() like list.skip(3).take(5) to get similar behavior though.最明显的区别是take()只能在开头使用元素,您可以将它与list.skip(3).take(5)类的skip()结合使用以获得类似的行为。
list.take() is lazy evaluated which works nice with functional style programming and might be more efficient if the elements aren't actually iterated over later. list.take()是惰性求值的,它适用于函数式编程,如果元素稍后没有真正迭代,它可能会更有效。
list.take() also is tolerant when there aren't as many elements in the list as requested. list.take()也可以容忍当列表中的元素没有要求的那么list.take() take() returns as many as available, getRange() throws. take()返回尽可能多的可用, getRange()抛出。 take() is available on all iterables (also streams), getRange() is only available by default on list. take()可用于所有可迭代对象(也包括流), getRange()仅在默认情况下可用于列表。

there are differences between take() and getRange() take()getRange()之间存在差异

take()拿()

This method returns iterable starting from index 0 till the count provided from given list.此方法返回从索引 0 开始直到从给定列表提供的计数的可迭代对象。

You can get the first count items of a List using take(count)您可以使用take(count)获取List的第一个计数项

var sportsList = ['cricket', 'tennis', 'football'];

print(sportsList.take(2));     // (cricket, tennis)

getRange()获取范围()

This method returns elements from specified range [start] to [end] in same order as in the given list.此方法以与给定列表中相同的顺序返回指定范围[start][end]中的元素。 Note that, start element is inclusive but end element is exclusive.请注意,开始元素是包含的,但结束元素是不包含的。

You can get a group of items by specifying the range in List using getRange() method.您可以通过使用getRange()方法在List指定范围来获取一组项目。

 var myList = [1, 2, 3, 4, 5];
 print(myList.getRange(1,4)); // (2, 3, 4)

 and also use
 var myList = [0, 'one', 'two', 'three', 'four', 'five'];
 myList.getRange(1, 3).toList();       // [one, two]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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