I have a LinkedList<T>
object where T is an arbitrary object which has a property named ID. I want search my collection using ID as search criteria.
Now I know I can search it using a while loop:
LinkedListNode<MyObject> element = myObject.First;
while (element != myObject.Last)
{
if (element.Value.ID == myID)
break;
element = element.Next;
}
But I'm wondering if there is a more elegant solution. Note that I need LinkedListNode<T>
as a result in order to navigate the list from there.
To search an element in a Linked List, we need to traverse the entire Linked List and compare each node with the data to be search and continue until a match is found. We need to begin the search process from the first node as random access is not possible in a Linked List. Pseudocode to search an element iteratively:
A LinkedList is a linear data structure used for storing the elements in a non-contiguous manner. The elements in a linked list are linked with each other using pointers. Or in other words, LinkedList consists of nodes where each node contains a data field and a reference (link) to the next node in the list.
We need to begin the search process from the first node as random access is not possible in a Linked List. 1) Initialize a node pointer, current = head. 2) Do following while current is not NULL a) current->key is equal to the key being searched return true. b) current = current->next 3) Return false
To store the elements in a linked list we use a doubly linked list which provides a linear data structure and also used to inherit an abstract class and implement list and deque interfaces. In Java, LinkedList class implements the list interface.
Will this give the result you expect?
Use @MartinLiversage answer and expand it to use the Find
method which is part of the LinkedList<T>
int id = 1;
LinkedListNode<IHaveID> nodes = null;
LinkedList<IHaveID> testList = new LinkedList<IHaveID>();
var item = testList.FirstOrDefault(x => x.ID == id);
if(item != null)
{
nodes = testList.Find(item);
}
You can write an extension method to get you a sequence of the nodes and search that:
public static IEnumerable<LinkedListNode<T>> Nodes<T>(this LinkedList<T> list)
{
for (var node = list.First; node != null; node = node.Next)
{
yield return node;
}
}
then you can do
var matchingNode = list.Nodes().FirstOrDefault(n => n.Value.Id == myId);
Same idea as Lee, but simpler code:
public static IEnumerable<LinkedListNode<T>> Nodes<T>(this LinkedList<T> list)
{
var node = list.First;
while (node != null)
{
yield return node;
node = node.Next;
}
}
EDIT
No need to use LINQ or extension methods. Simply use .Find() - it returns a LinkedListNode
var node = list.Find(5);
Note: For this to work your model with the id would need to override object.Equals to compare ID's (and therefore object.GetHashCode)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With