开发者

C# linked lists

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 th开发者_Python百科e first 20. I really want to avoid for loops.

Thanks,

PM


Use Linq?

myLinkedList.Take(20).ToArray()

or

myLinkedList.Skip(5).Take(20).ToArray()


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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜