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?
If you need to update, use FindIndex
:
int index = myList.FindIndex(n => n == "John");
myList[index] = "Anna";
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
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