Home > Back-end >  Build a list recursively - C# LINQ
Build a list recursively - C# LINQ

Time:07-20

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))
}

CodePudding user response:

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

CodePudding user response:

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;
}

  • Related