简体   繁体   中英

Build a list recursively - C# LINQ

I'm building a list where each element I add tells me which element I should add next. Is there a faster way to do this using LINQ?

List<Element> result = new List<Element>() {firstElement};
while (result.Last().nextElement != null) {
    result.Add(result.Last().nextElement))
}

It seems that you want to build linked list , if it is what you want I am suggesting to use Generic Linked List class.

The LinkedList class have all method to handle, add/remove, clear, search and ... that you may need. Also it has better performance and memory management.

you can find more help and example on msdn here

You should avoid the calls to result.Last() . We cannot know how it is implemented. In worst case it will create an enumerator every time you call it and loop through the whole list. Twice per loop! This will generate loads of object creation and garbage collection.

It would be far easier to hold a current item and just add it to the list.

List<Element> result = new();
var current = firstElement;
while(current != null) {
  result.Add(current);
  current = current.NextElement;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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