0

I have a arraylist with string(codes) and I want to control whether a string is duplicate in this arraylist. if the string is duplicate i want a other code to the arraylist.

my code:

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);
}
4
  • Could you use List<string>? A better choice. Just saying.. Commented Jul 15, 2013 at 12:20
  • You can check if the content is already available using perhaps, List#contains() in Java , not sure of C# ! Commented Jul 15, 2013 at 12:21
  • 1
    stackoverflow.com/questions/4564095/… Commented Jul 15, 2013 at 12:21
  • 1
    List<T>.Contains() in C# Commented Jul 15, 2013 at 12:22

2 Answers 2

3

Add this in place of your list.add(code);. This method checks whether the item is already in the array list.

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 for more information about the List<T>.Contains() method.

Sign up to request clarification or add additional context in comments.

2 Comments

And there is probably an else here too right? The OP stated they wanted to add a different code if it's a duplicate -- or at least I think that's what they meant. :D
@MichaelPerrenoud Good point. I have added the else branch, and comments to make this clear.
0

You can also use the LINQ method Distinct to remove any duplicates after you have populated your list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.