How do I get the n-th element in a LinkedList?

前端 未结 4 877
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 14:26

How can I get the n-th element of a LinkedList instance? Is there a built-in way or I might need to introduce my own implementation? For example an extension method?

相关标签:
4条回答
  • 2020-12-11 15:02

    The ElementAt extension method will do it:

    // This is 0-based of course
    var value = linkedList.ElementAt(n);
    

    Don't forget this is an O(n) operation because LinkedList<T> doesn't provide any more efficient way of accessing an item by index. If you need to do this regularly, it suggests that you shouldn't be using a linked list to start with.

    0 讨论(0)
  • 2020-12-11 15:06

    You can do it with LINQ as in list.ElementAt(n) or list.Skip(n - 1).First() , but if you find yourself making indexed access into a linked list you are probably doing something wrong (linked lists do not efficiently support this operation). Perhaps another data structure would be more appropriate?

    0 讨论(0)
  • 2020-12-11 15:20

    You can use the ElementAt() enumerable extension method. The reason LinkedList doesn't support random access natively is because it's a rather inefficient operation for the data structure. If you're going to be doing it often you should think about using a more appropriate data structure.

    0 讨论(0)
  • 2020-12-11 15:23

    I needed to get the second element of my list (to update a value on the 1st item based on the 2nd)

    Assuming you're taking the necessary steps to ensure you do have two items you can simply do this :

    list.First.Next.Value
    
    0 讨论(0)
提交回复
热议问题