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!

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

    Very cool – thanks

    Like

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

    thanks a ton..!!

    Like

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

    Like

    • 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!

      Like

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

Leave a comment