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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Oct 2, 2007, 6:31 AM
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/
Dino SPosted Oct 2, 2007, 3:47 AM
Thx Alan. Do you have any idea where i can find a good C# book to study? any specific C# book?
Many thx
/Dino
AlanPosted Oct 1, 2007, 12:30 PM
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();
}
}