Zeus
Zeus

Reputation: 1600

How to update node value in a linkedlist using linq

I'd like to update a node value in a linked list using linq. Traversing the list, finding the right node and updating the value works, but I think a linq method could be cleaner.

This is my attempt which gives a compile error cannot convert lambda expression to type <Main.Globals.Node> because it is not a delegate type:

// get IV value where Node BookID=4
var val = Globals.BookLL.Where(B => B.BookID == 4).Select(B => B.IV).Single();

// can update first node using this method
Globals.BookLL.First.Value.IV = 999;

// can upddate IV by traversing list
LinkedListNode<Globals.Node> Current = Globals.BookLL.First;
while (Current != null)
            {
                if(Current.Value.BookID==4)
                {
                    Current.Value.IV = 444;
                }
                Current = Current.Next;
            }

   // how can you update IV using linq?
   Globals.BookLL.Find(B => B.BookID == 4).Value.IV = 999;        // cannot convert lambda expression to type <Main.Globals.Node> because it is not a delegate type

Thanks for any help.

Upvotes: 0

Views: 185

Answers (3)

fubo
fubo

Reputation: 45967

If you use

Globals.BookLL val = Globals.BookLL.Single(B => B.BookID == 4);

to determine the item, you can use Find()

Globals.BookLL.Find(val).Value.IV = 999; 

to change it's value

Upvotes: 2

TVOHM
TVOHM

Reputation: 2742

Globals.BookLL.Single(b => b.BookId == 4).IV = 44;

You can use single if BookIds are unique.

Upvotes: 2

Jakub Jankowski
Jakub Jankowski

Reputation: 731

Globals.BookLL.Find(B => B.BookID == 4)

This returns an IEnumerable<Globals.Node>, you should use LINQ's First():

Globals.BookLL.First(B => B.BookID == 4).Value.IV = 999;

Upvotes: 0

Related Questions