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
Very cool – thanks
LikeLike
thanks a ton..!!
LikeLike
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);
LikeLike
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!
LikeLike
Better use a LINQ expression:
http://stackoverflow.com/questions/9673/remove-duplicates-from-array
LikeLike