ArrayList
Hi. i am a beginner at programing. can someone pleas tell me how to do an arraylist which check if an items has been added more than once?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
AlanRank #669 · 3.6K reputationPosted Oct 1, 2007, 8:30 AM EDT
Here's a possible approach which still works if the ArrayList contains elements of different types:
using System;
using System.Collections;
class Program
{
static void Main()
{
ArrayList al = new ArrayList();
al.Add(123);
al.Add("hello");
al.Add(456.78);
al.Add("hello");
al.Add(456.78);
al.Add(true);
al.Add(new MyClass());
al.Add(new MyClass()); // different obect, so not duplicated
MyClass mc = new MyClass();
al.Add(mc);
al.Add(mc); //same object, so duplicated
bool containsDuplicates = false;
for (int i = 0; i < al.Count - 1; i++)
{
if (al.IndexOf(al[i], i + 1) > -1)
{
Console.WriteLine("{0} is duplicated", al[i]);
if (!containsDuplicates) containsDuplicates = true;
}
}
if (!containsDuplicates)
Console.WriteLine("There are no duplicated objects");
Console.ReadLine();
}
}
class MyClass
{
static int lastId;
public readonly int Id;
public MyClass()
{
Id = ++lastId;
}
public override string ToString()
{
return "MyClass object #" + Id.ToString();
}
}
Dino S5 reputationPosted Oct 1, 2007, 11:47 PM EDT
Thx Alan. Do you have any idea where i can find a good C# book to study? any specific C# book?
Many thx
/Dino
AlanRank #669 · 3.6K reputationPosted Oct 2, 2007, 2:31 AM EDT
Hi Dino,
As luck would have it, Mahesh Chand has just written a free book for C# beginners which can be downloaded here:
http://www.c-sharpcorner.com/UploadFile/mahesh/csp08202007084545AM/csp.aspx
Other good online resources to check out include the following (the second one's best if you already know a bit of C/C++):
http://www.publicjoe.co.uk/csharp/csharp.html
http://www.charlespetzold.com/dotnet/