如何替换VB.NET中List(Of String)中的项目? [英] How do I replace an item in List(Of String) in VB.NET?

查看:471
本文介绍了如何替换VB.NET中List(Of String)中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个项目有问题.在其中,我面临着索引问题的障碍.我有一个以这种方式实例化的列表:

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.

有人可以帮我吗?

推荐答案

frmMain.answers(i) = correctanswer

这是一个小例子:

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

这应该打印:

答案A

答案C

这篇关于如何替换VB.NET中List(Of String)中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆