find the sum of all nodes in a linked list in csharp

To find the sum of all nodes in a linked list in C#, you can traverse the linked list and keep adding the value of each node to a sum variable. Here's the code for the method:

main.cs
public int LinkedListSum(LinkedList<int> list)
{
    int sum = 0;
    LinkedListNode<int> currentNode = list.First;
    while (currentNode != null)
    {
        sum += currentNode.Value;
        currentNode = currentNode.Next;
    }
    return sum;
}
252 chars
12 lines

This method takes a LinkedList<int> as input and returns the sum of all nodes. It initializes a variable sum to 0 and starts traversing the linked list from the first node. It keeps adding the value of each node to the sum variable and moves to the next node. The loop continues until the end of the linked list is reached (i.e., currentNode becomes null). Finally, the method returns the sum variable, which has the total sum of all nodes in the linked list.

gistlibby LogSnag