Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ update item List<string>

Tags:

c#

linq

I have problem with updating a single item under List<string> that matches a different string using LINQ. Let's say that I have a list of names and I want to check if name "John" already exists in my list. If yes, then replace "John" with "Anna".

Here is what I do:

var sItem = myList.First(n=> n == "John"); //I am 100% sure that John exists, that\s why I use .First
sItem = "Anna";

This is how it should work, but when I check my List (myList) after the process, the original item is still there (I can still see John, instead of Anna). I also tried to implement INotifyChanged on the List, but still no result.

What am I doing wrong?

like image 355
Robert J. Avatar asked Jul 30 '14 18:07

Robert J.


2 Answers

If you need to update, use FindIndex:

int index = myList.FindIndex(n => n == "John");
myList[index] = "Anna";
like image 92
Lee Avatar answered Sep 23 '22 11:09

Lee


You are assigning the result of linq query to a string variable. That is not the element of list but a variable that is also referencing the element of that list. Changing the value of variable sItem will define a new string that will be referenced by the sItem and the item in the list remains unchanged.

You can use FindIndex to get the index of element in the array and use it to refer to list element.

int index = myList.FindIndex(n => n == "John");
myList[index] = "Anna";

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire List.

Edit

When one string variable is assigned to other. They both would be referencing the same string but when you assign a different string to second variable for instance then they both referencing different strings. See the following example from answer of Eric Lippert.

a----------------------Hello

Then you say that "b = a", which means attach another piece of string to the same thing that a is attached to:

a----------------------Hello
                      /
b---------------------

Then you say "now attach b to Hi"

a----------------------Hello

b----------------------Hi
like image 36
Adil Avatar answered Sep 20 '22 11:09

Adil