tags:

views:

55

answers:

3

Hey,

very basic question, but is there any ToArray-like function for c# linked lists that would return an array of only part of the elements in the linkedlist.

e.g.: let's say my list has 50 items and I need an array of only the first 20. I really want to avoid for loops.

Thanks,

PM

+6  A: 

Use Linq?

myLinkedList.Take(20).ToArray()

or

myLinkedList.Skip(5).Take(20).ToArray()
spender
+4  A: 

You say you "really want to avoid for loops" - why?

If you're using .NET 3.5 (or have LINQBridge), it's really easy:

var array = list.Take(20).ToArray();

... but obviously that will have to loop internally.

Note that this will create a smaller array if the original linked list has fewer than 20 elements. It's unclear whether or not that's what you want.

Something is going to have to loop internally, sooner or later - it's not like there's going to be a dedicated CPU instruction for "navigate this linked list and copy a fixed number of pointers into a new array". So the question is really whether you do it or a library method.

If you can't use LINQ, it's pretty easy to write the equivalent code yourself:

int size = Math.Min(list.Count, 20);
MyType[] array = new MyType[size];
var node = list.First;
for (int i = 0; i < size; i++)
{
    array[i] = node.Value;
    node = node.Next;
}

That will actually be slightly more efficient than the LINQ approach, too, because it creates the array to be exactly the right size to start with. Yes, it uses a loop - but as I say, something's got to.

Jon Skeet
I don't mind the internal looping I just missed the Take method while going through the linked-list method list. I got caught up on Select, which is really not what I need.
A: 

If you're using the LinkedList collection class (from System.Collections.Generic), you can use LINQ to get it:

var myArray = list.Take(20).ToArray();
Jim Mischel