简体   繁体   中英

How do I replace an item in List(Of String) in VB.NET?

I am having issues with one of my projects. In it, I am facing the obstacle of indexing problems. I have a list instantiated this way:

Public answers As List(Of String) = New List(Of String)

Items are added to this list by this code:

Dim correctanswer As String = "" 'except the user changes the value with the GUI
frmMain.answers.Add(correctanswer)

(And by the way, I'm only including the relevant parts to this monster of a project, so I will post more code by request, if needed.)

This code works fine; however, I am attempting to allow the user to modify each list item at will. I tried doing that by the following method:

frmMain.answers.ElementAt(i) = correctanswer '(where 'i' is the index in question)

and the compiler doesn't like that. It's yelling at me.

Expression is not a value and therefore cannot be the target of an assignment.

Now, I've faced this issue before when I was trying to replace items in a similar list; however, those items were my own custom classes. This is just a list of strings. I tried another method as well:

frmMain.RemoveAt(i)
frmMain.Insert(i, correctanswer)

The problem with that is, the order of the list gets mixed up. The indexes move around, and it ultimately makes a mess rather than doing what I want it to.

Can someone please give me a hand?

frmMain.answers(i) = correctanswer

Here is a small example:

Dim answers As List(Of String) = New List(Of String)
answers.Add("Answer A")
answers.Add("Answer B")
answers.Add("Answer C")
Dim correctanswer As String = ""

answers(1) = correctanswer
For Each str As String In answers
Console.WriteLine(str)
Next

This should print:

Answer A

Answer C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM