list.Take(100).ToList() vs. list.GetRange(0,100)

前端 未结 5 1721
臣服心动
臣服心动 2021-02-19 11:57
List attendees = new List();
foreach ...
// Error: \"There are too many target users in the email address array\"
// for more tha         


        
5条回答
  •  长情又很酷
    2021-02-19 12:47

    There is a minor between Take and GetRange. Take will evaluate lazily until you force it to evaulate into ToList(). This can change behavior.

    Consider the pseudo code.

    List myList = new List() {1,2,3,4,5,6};
    IEnumerable otherList = myList.Take(3);  // {1,2,3};
    myList.RemoveRange(0,3);
    // myList = {4, 5, 6}
    // otherList = {4, 5, 6}
    

    Now change this example to following code.

    List myList = new List() {1,2,3,4,5,6};
    IEnumerable otherList = myList.Take(3).ToList();  // {1,2,3};
    myList.RemoveRange(0,3);
    // myList = {4, 5, 6}
    // otherList = {1, 2, 3}
    

    Doing ToList() can change the behavior of Take or GetRange depending upon what operations you are using next. It is always easier to use GetRange since it will not cause any unknown bugs.

    Also GetRange is efficient.

提交回复
热议问题