Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 132,180 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,446 people online right now. Registration is fast and FREE... Join Now!




Help with ArrayList

 
Reply to this topicStart new topic

Help with ArrayList, do not got my arraylist (search) to work

micke
post 5 Oct, 2008 - 10:24 AM
Post #1


New D.I.C Head

*
Joined: 25 Aug, 2008
Posts: 14


My Contributions


Hi,

I'm trying to search an array list, but i do not succed. It is sorting correct, but do not found
anything i search for. tried with an IndexOf and a BinarySearch but dosen't seems to work.



the code :

CODE


ArrayList myArrayList = new ArrayList();

            myArrayList.Add(new Student("Mikael Andersson", "0000-00-00", "C# Programming", "10"));
            myArrayList.Add(new Student("Anna Martinsson", "0000-00-00", "Visal Basic Programming", "8"));
            myArrayList.Add(new Student("Hampus Martinsson", "0000-00-00", "C# Programming", "7"));


case 2:
                        Console.Write("Search CourceName : <cource>\n");
                        string searchCource = Console.ReadLine();

                        // Sort items
                        myArrayList.Sort();

                        int index = 0;

                        // List Student items
                        foreach (Student item in myArrayList)
                        {
                            Console.WriteLine("\t[{0}]:\t{1}", index++, item);
                        }


                       Console.WriteLine(myArrayList.IndexOf(searchCource));

                        // Perform a search
                        Console.WriteLine("searchCource found at index {0}", myArrayList.BinarySearch(searchCource));


thanks for any help. biggrin.gif

This post has been edited by micke: 5 Oct, 2008 - 10:25 AM
User is offlineProfile CardPM

Go to the top of the page

Martyr2
post 5 Oct, 2008 - 11:00 AM
Post #2


Programming Theoretician

Group Icon
Joined: 18 Apr, 2007
Posts: 5,012



Thanked 171 times

Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions


Well remember that your arraylist is going to be full of Student objects. So in order to do a sort for instance you are going to have to tell C# how to compare your student objects. So hopefully you have done that. If not, look into implementing the IComparable interface on your Student class and then you will need to define the compareTo() method.

You can see an example of this at the following page...

IComparable Interface (MSDN)

Anything that sorts will need such an interface if it is a customized object you are storing so that it knows how to compare each for sorting.

You also have to understand that since your arraylist also stores objects that the item you pass to BinarySearch is also an object. The BinarySearch method which takes one parameter is going to also use the default comparer to see if the two objects are equal. Now BinarySearch also takes other parameters optionally which allows you to specializing a comparing function which you can then use to do the comparison.

But for simplicity sake, either create a student object that is identical to the one stored in the ArrayList or do a search algorithm which simply looks at objects and asks the object to return values. Below is an example of how this is done using a sequential search....

csharp

ArrayList myArrayList = new ArrayList();

myArrayList.Add(new Student("Mikael Andersson", "0000-00-00", "C# Programming", "10"));
myArrayList.Add(new Student("Anna Martinsson", "0000-00-00", "Visal Basic Programming", "8"));
myArrayList.Add(new Student("Hampus Martinsson", "0000-00-00", "C# Programming", "7"));


Console.Write("Search CourceName : <cource>\n");
string searchCource = Console.ReadLine();


// Sort items
//myArrayList.Sort();

int index = 0;

// List Student items
foreach (Student item in myArrayList)
{
// We implemented a ToString function and we compare the
// search terms to the item by asking the item to return its
// value. If they match, we found the item.
if (searchCource == item.ToString())
{
Console.WriteLine("Found at element: " + index);
}
index++;
}



Again this is a sequential search (for simplicity) to show you how each item in the arraylist is an object so we have to ask it to reveal its information. Otherwise if we use the binarysearch we can pass it a student object to look for (not a string in this case). IndexOf works similar. You pass it an object to look for. Now if that object is a string, fine, pass it a string but in this case you would have to pass it a Student object to look for in the collection.

Hope I am making sense to you. smile.gif

This post has been edited by Martyr2: 5 Oct, 2008 - 11:01 AM
User is offlineProfile CardPM

Go to the top of the page

micke
post 6 Oct, 2008 - 10:03 AM
Post #3


New D.I.C Head

*
Joined: 25 Aug, 2008
Posts: 14


My Contributions


Hi, Thanks for the answer. I'm doing an sort with IComarable, but since this is my first ArrayList i'm not quit getting it how it works. If i under stand correctly the myArrayList looks like this

[0] - Student
[1] - Student
[2] - Student

and every Student object contains name, birth, cource, grade. I was trying do like this :
if (myArrayList [index].name eq searchCource)
{
print(student);
}

but that diden't work i also tried :

Console.WriteLine(myArrayList.IndexOf("Mikael"));
returned three -1 what i belive is that it wasen't found, but tried to print out the one it found but wasen't enable to.

adding the hole code : program.cs

csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace HomeWork3_6
{
class Program
{
static void Main(string[] args)
{

ArrayList myArrayList = new ArrayList();

Console.WriteLine("Adding three Student objects to myArrayList");
myArrayList.Add(new Student("Mikael Andersson", "0000-00-00", "C# Programming", "10"));
myArrayList.Add(new Student("Anna Martinsson", "0000-00-00", "Visal Basic Programming", "8"));
myArrayList.Add(new Student("Hampus Martinsson", "0000-00-00", "C# Programming", "7"));

bool done = false;
do
{
Console.WriteLine("Select one of the following:");
Console.WriteLine("\t1 -- Add student");
Console.WriteLine("\t2 -- Search Cource");
Console.WriteLine("\t3 -- Display all (sorted list)");
Console.WriteLine("\t4 -- Remove student");
Console.Write("Enter Your selection (0 to exit): ");
string strSelection = Console.ReadLine();
int iSel;
try
{
iSel = int.Parse(strSelection);
}
catch (FormatException)
{
Console.WriteLine("\r\nWhat?\r\n");
continue;
}
Console.WriteLine("You selected " + iSel);
switch (iSel)
{
case 0:
done = true;
break;

case 1:
Console.Write("Enter Name : <firstname> <lastname>\n");
string name = Console.ReadLine();

Console.Write("Enter Birtday : <xxxx-xx-xx>\n");
string birth = Console.ReadLine();

Console.Write("Enter CourceName : <cource>\n");
string cource = Console.ReadLine();

Console.Write("Enter Grade : <grade>\n");
string grade = Console.ReadLine();

myArrayList.Add(new Student(name, birth, cource, grade));

Console.WriteLine("\nArrayList - Added new entry");

foreach (Student i in myArrayList)
{
Console.WriteLine(" " + i);
}
break;

case 2:
Console.Write("Search CourceName : <cource>\n");
string searchCource = Console.ReadLine();

// Sort items
myArrayList.Sort();

int index = 0;

// List Student items
foreach (Student item in myArrayList)
{
Console.WriteLine(myArrayList.IndexOf("Mikael"));

// We implemented a ToString function and we compare the
// search terms to the item by asking the item to return its
// value. If they match, we found the item.
if (searchCource == item.ToString())
{
Console.WriteLine("Found at element: " + index);
}
index++;
}

// Perform a search
//Console.WriteLine("'Mikael' found at index {0}", myArrayList.BinarySearch("Mikael"));

break;

case 3:

Console.WriteLine("\nArrayList - Before sorted ");

foreach (Student i in myArrayList)
{
Console.WriteLine(" " + i);
}

//sort the array list
myArrayList.Sort();

Console.WriteLine("\nArrayList - Sorted by Name");

foreach (Student i in myArrayList)
{
Console.WriteLine(" " + i);
}


break;

case 4:

Int32 myIndex = new Int32();
myIndex = myArrayList.IndexOf(0);
Console.WriteLine("test : {0}", myIndex);


break;
default:
Console.WriteLine("You selected an invalid number: {0}\r\n", iSel);
continue;
}
Console.WriteLine();
} while (!done);

Console.WriteLine("\nGoodbye!");
}
}
}




Student.cs

csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;


namespace HomeWork3_6
{
class Student : IComparable
{
string name;
string birth;
string cource;
string grade;

//Empty Constructor
public Student()
{
}

//Constructor
public Student(string aName, string aBirth, string aCource, string aGrade)
{
name = aName;
birth = aBirth;
cource = aCource;
grade = aGrade;
}

public int CompareTo(object obj)
{
Student e = (Student)obj;
return this.name.CompareTo(e.name); // ascending
}


public override string ToString()
{
return String.Format("{0} {1} {2} {3}", name, birth, cource, grade);
}
}
}




am i doing it totaly wrong? thanks for the help!

This post has been edited by micke: 6 Oct, 2008 - 10:08 AM
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 6 Oct, 2008 - 10:19 AM
Post #4


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,960



Thanked 95 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


Do you have to use ArrayList, because List<Student> is a far more elegant solution and makes the things you're trying to do easier.

As to your current problem. Your CompareTo is being a little narrow minded:
csharp

public int CompareTo(object obj) {
Student e = (Student)obj;
return this.name.CompareTo(e.name); // ascending
}


First, it's assuming obj is of type Student, which it needn't be. It's also not giving string a chance.

Try something like this:
csharp

public int CompareTo(object obj) {
// it's null, leave now
if (obj==null) { return -1; }

if (this.GetType()==obj.GetType()) {
// yay, one of us
Student e = (Student)obj;
return this.name.CompareTo(e.name); // ascending
}

// for everthing else, there's a string compare
return this.name.CompareTo(obj.ToString()); // ascending
}

User is online!Profile CardPM

Go to the top of the page

micke
post 7 Oct, 2008 - 08:00 AM
Post #5


New D.I.C Head

*
Joined: 25 Aug, 2008
Posts: 14


My Contributions


Hi, thanks!

but sorry now am i lost, i thought the CompareTo was only for sorting?

is List<Student> easier? never heard of!

but the problems seems to be that it dosen't search inside the Object, since if i only add Console.WriteLine(myArrayList.IndexOf("Mikael")); does that not only search for an Object named Mikael and not inside it?

User is offlineProfile CardPM

Go to the top of the page

baavgai
post 7 Oct, 2008 - 09:27 AM
Post #6


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,960



Thanked 95 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


QUOTE(micke @ 7 Oct, 2008 - 12:00 PM) *

i thought the CompareTo was only for sorting?

is List<Student> easier? never heard of!


Sorry for the confusion. Yes, CompareTo is for sorting. The IndexOf uses the Equals method. It's just that if you implement CompareTo you pretty much get Equals for free:
csharp

public override bool Equals(object obj) {
return this.CompareTo(obj) == 0;
}


However, you're not just asking for it to compare to name, but to a partial name. You essentially want to do a search. You'll have write your own for loop for that. Or use a List<>...

Here's some code. Hope it makes sense and gives you some ideas.
csharp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;

namespace HomeWork3_6 {

class Student : IComparable {
string name;
string birth;
string cource;
string grade;

//Empty Constructor
public Student() { }

//Constructor
public Student(string aName, string aBirth, string aCource, string aGrade) {
name = aName;
birth = aBirth;
cource = aCource;
grade = aGrade;
}

// expose name to public
public string Name { get { return this.name; } }

public int CompareTo(object obj) {
if (obj==null) { return -1; }
if (this.GetType()==obj.GetType()) {
Student e = (Student)obj;
return this.name.CompareTo(e.name); // ascending
}
return this.name.CompareTo(obj.ToString()); // ascending
}

// overide Equals, to lookup by name.
public override bool Equals(object obj) {
return this.CompareTo(obj) == 0;
}

// if you override Equals, you must override hash code
// just give it the hashCode of name and it's fine
public override int GetHashCode() {
return this.name.GetHashCode();
}

public override string ToString() {
return String.Format("{0} {1} {2} {3}", name, birth, cource, grade);
}
}

class Program {
protected ArrayList myArrayList = new ArrayList();
protected List<Student> studentList = new List<Student>();

public void AddStudent(Student s) {
myArrayList.Add(s);
studentList.Add(s);
}

protected void TestArrayList() {
Debug.WriteLine("TestArrayList");
Debug.WriteLine("Items:");
foreach (Student item in myArrayList) { Debug.WriteLine(item); }
// this works, with the Equals set up
Debug.WriteLine(myArrayList.IndexOf("Anna Martinsson"));

// this doesn't work, and shouldn't
Debug.WriteLine(myArrayList.IndexOf("Mikael"));
}

protected void TestStudentList() {
Debug.WriteLine("TestStudentList");
Debug.WriteLine("Items:");
foreach (Student item in studentList) { Debug.WriteLine(item); }

//Debug.WriteLine(studentList.IndexOf("Mikael"));
// here we write a custom search for what we want
Debug.WriteLine(studentList.FindIndex(delegate(Student item) {
return item.Name.StartsWith("Mikael");
}));
}


public void Test() {
AddStudent(new Student("Mikael Andersson", "0000-00-00", "C# Programming", "10"));
AddStudent(new Student("Anna Martinsson", "0000-00-00", "Visal Basic Programming", "8"));
AddStudent(new Student("Hampus Martinsson", "0000-00-00", "C# Programming", "7"));
TestArrayList();
TestStudentList();
}

static void Main(string[] args)
{
Program pgm = new Program();
pgm.Test();
}
}
}

User is online!Profile CardPM

Go to the top of the page

micke
post 7 Oct, 2008 - 11:26 PM
Post #7


New D.I.C Head

*
Joined: 25 Aug, 2008
Posts: 14


My Contributions


Thanks i will try this tonight.

btw.

csharp
        public int CompareTo(object obj) {  
if (obj==null) { return -1; }
if (this.GetType()==obj.GetType()) {
Student e = (Student)obj;
return this.name.CompareTo(e.name); // ascending
}
return this.name.CompareTo(obj.ToString()); // ascending
}

// overide Equals, to lookup by name.
public override bool Equals(object obj) {
return this.CompareTo(obj) == 0;
}

// if you override Equals, you must override hash code
// just give it the hashCode of name and it's fine
public override int GetHashCode() {
return this.name.GetHashCode();
}



if i for example also wanted to search for an cource do i need to add another CompareTo ? or do i then need an function called searchCource but isen't then CompareTo only checking name not cource? any tutorials where i can find more information about this? stupid questions, but i'm trying to learn smile.gif

thanks for the help so far ...
User is offlineProfile CardPM

Go to the top of the page

baavgai
post 8 Oct, 2008 - 03:44 AM
Post #8


Dreaming Coder

Group Icon
Joined: 16 Oct, 2007
Posts: 1,960



Thanked 95 times

Dream Kudos: 475

Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions


QUOTE(micke @ 8 Oct, 2008 - 03:26 AM) *

do i need to add another CompareTo?


One CompareTo per class and one Equals, come to that.

That's the reason for using a "delgate" for such operations, the way the generics do. Here's more info on that:
http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx
http://csharpindepth.com/Articles/Chapter5/Closures.aspx
User is online!Profile CardPM

Go to the top of the page

micke
post 10 Oct, 2008 - 02:40 PM
Post #9


New D.I.C Head

*
Joined: 25 Aug, 2008
Posts: 14


My Contributions


Thanks, i finally solved it smile.gif
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 11/21/08 03:44PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month