Home > Uncategorized > Useful c# function – remove duplicates

Useful c# function – remove duplicates

This is a useful c# function, that removes duplicates from an arraylist
 

public ArrayList RemoveDups(ArrayList items)

{

ArrayList noDups = new ArrayList();

foreach(string strItem in items)

{

if (!noDups.Contains(strItem.Trim()))

{

noDups.Add(strItem.Trim());

}

}

noDups.Sort();

return noDups;

}

 

Handy!

Advertisements
Categories: Uncategorized
  1. Brian
    December 21, 2010 at 5:42 pm

    Very cool – thanks

  2. nawfal
    April 8, 2011 at 12:20 pm

    thanks a ton..!!

  3. August 5, 2011 at 2:15 pm

    I can’t get this to work – sorry, but I am a noob in my first c# class.
    Here is what I have (please note that I switched out “noDups” with “trimmage” – I was already using the name noDups throughout my code for my initial array list. I need each item to show up only twice in a random order:

    ArrayList noDups = new ArrayList();

    public void RandomOrder(ArrayList arrList)
    {
    Random r = new Random();
    for (int cnt = 0; cnt < arrList.Count; cnt++)
    {
    object tmp = arrList[cnt];
    int idx = r.Next(arrList.Count – cnt) + cnt;
    arrList[cnt] = arrList[idx];
    arrList[idx] = tmp;
    }

    }

    public ArrayList RemoveDups(ArrayList noDups)

    {
    ArrayList trimmage = new ArrayList();

    foreach(string strItem in noDups)
    {
    if (!trimmage.Contains(strItem.Trim()))
    {
    trimmage.Add(strItem.Trim());
    }
    }

    return trimmage;
    }

    public void randomAssign()
    {

    noDups.Add("A");
    noDups.Add("A");
    noDups.Add("B");
    noDups.Add("B");
    noDups.Add("C");
    noDups.Add("C");
    noDups.Add("D");
    noDups.Add("D");
    noDups.Add("E");
    noDups.Add("E");
    noDups.Add("F");
    noDups.Add("F");
    RandomOrder(noDups);
    RemoveDups(noDups);

    • August 5, 2011 at 2:55 pm

      Please note that a problem with this is that I need two instances of each string item….Ex: I need two “A”…..write now, this code is producing more than two!

  4. November 2, 2012 at 8:20 pm
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: