如何控制重复值的ArrayList
本文关键字:ArrayList 何控制 控制 | 更新日期: 2023-09-27 18:22:25
我有一个带字符串(代码)的数组列表,我想控制这个数组列表中的字符串是否重复。如果字符串重复,我希望数组列表中有其他代码。
我的代码:
private void btn_Create_Click(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
try
{
list = DoDeserialize();
}
catch (Exception ex)
{
lbl_status.Text = ex.Message;
}
string code = GetCode(7);
code = "2 - " + code;
int test = list.IndexOf(code);
txt_Code.Text = code;
lbl_status.Text = "Code wurde erstellt";
list.Add(code);
DoSerialize(list);
}
将其添加到list.add(code);
的位置。此方法检查该项是否已在数组列表中。
if(!list.Contains(code))
{
// The code does not already exist in the list, so add it
list.add(code);
} else {
// The code already exists, do something here.
}
有关List<T>.Contains()
方法的更多信息,请参见此处。
您还可以使用LINQ方法Distinct
在填充列表后删除任何重复项。