如何控制ArrayList的重复值?

时间:2013-07-15 12:19:29

标签: c# arraylist duplicates

我有一个带字符串(代码)的arraylist,我想控制这个arraylist中的字符串是否重复。如果字符串是重复的我想要arraylist的其他代码。

我的代码:

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);
}

2 个答案:

答案 0 :(得分:3)

添加此代替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.
}

See here了解有关List<T>.Contains()方法的更多信息。

答案 1 :(得分:0)

您还可以在填充列表后使用 LINQ 方法Distinct删除所有重复项。