471,605 Members | 1,503 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,605 software developers and data experts.

Sorting & ArrayLists

Hi Eveyone,

I'm trying to sort my ArrayList, but I'm getting stumped. Hopefully someone
can help me out. I'm using C# Windows forms, but Console app for testing.
What I am doing is pulling my data from my database and putting the data
into an ArrayList. from there I want to be able to sort the data out. This
is where I"m getting stumped. Getting at, and viewing the data is all good
until I try to use "myArrayList.Sort". Trying various sort methods pull
errors ie: "Specified IComparer threw an exception". As for me data I won't
know the amount of data that there will be in the database, just that I want
to sort the first row of my arraylist. A sample of my code follows. Txs in
advance and Any and all help is appreciated.

using System;
using System.Collections;
using System.Data.OleDb;

namespace Ch11Ex01_ArrayList
{
class Class1
{
static void Main(string[] args)
{
try
{ //Connetion to DataBase
OleDbConnection myConnection = new OleDbConnection(@"Provider =
Microsoft.Jet.OLEDB.4.0;Data Source = C:\Host.mdb");
//Open Connection to DataBase
myConnection.Open();
//SQL Command for myConnection
OleDbCommand myCommand = myConnection.CreateCommand();
//Initialize SQL SELECT command to retrieve data
myCommand.CommandText = "SELECT * FROM Food_Lunch_Menu";
//Create DataReader
OleDbDataReader myDataReader = myCommand.ExecuteReader();

ArrayList myArrayList = new ArrayList();

while(myDataReader.Read())
{
myName myItem = new myName(myDataReader["Index"].ToString());
myItem.myIndex(myDataReader["Name"].ToString());
myArrayList.Add(myItem);
Console.WriteLine(myItem.Name + " " + myItem.Index);
}

myArrayList.Sort(0, 0, null); <-Problem Spot

foreach(myClass myItems in myArrayList)
{
Console.WriteLine(myItems.Name + " " + myItems.Index);
}
myDataReader.Close();
myConnection.Close();
}
catch(Exception myException)
{
Console.WriteLine(myException.Message);
}
}
}
}
Jan 26 '06 #1
5 3261
> Hi Eveyone,

I'm trying to sort my ArrayList, but I'm getting stumped. Hopefully
someone can help me out. I'm using C# Windows forms, but Console app
for testing. What I am doing is pulling my data from my database and
putting the data into an ArrayList. from there I want to be able to
sort the data out. This is where I"m getting stumped. Getting at, and
viewing the data is all good until I try to use "myArrayList.Sort".
Trying various sort methods pull errors ie: "Specified IComparer threw
an exception". As for me data I won't know the amount of data that
there will be in the database, just that I want to sort the first row
of my arraylist. A sample of my code follows. Txs in advance and Any
and all help is appreciated.
[snippage]
myArrayList.Sort(0, 0, null); <-Problem Spot


Here is where you're wrong. You'll need to create a custom IComparer for
this. Also, .Sort(0,0) will sort nothing. You need to call .Sort(0, test.Count,
new MyNameComparer())

Example:

[STAThread]
private static void Main()
{
ArrayList test = new ArrayList();

test.Add(new MyName("Zara"));
test.Add(new MyName("Stephen"));
test.Add(new MyName("Mike"));
test.Add(new MyName("Laura"));
test.Add(new MyName("Barbara"));
test.Add(new MyName("Adam"));

test.Sort(0, test.Count, new MyNameComparer());

foreach (MyName s in test)
{
Console.WriteLine(s.Name);
}

Console.ReadLine();
}

public class MyNameComparer : IComparer
{
public int Compare(object x, object y)
{
if(!(x is MyName) || !(y is MyName))
{
throw new ArgumentException("Objects must be of type MyName.");
}

string xName = (x as MyName).Name;
string yName = (y as MyName).Name;

return xName.CompareTo(yName);
}
}

public class MyName
{
private string name;

public MyName(string name)
{
this.name = name;
}

public string Name
{
get { return name; }
set { name = value; }
}
}
Jan 26 '06 #2
> myArrayList.Sort(0, 0, null); <-Problem Spot
The 3-rd parameter is null it must not be null if you want to sort arralist
items with specific comprarer
Wath the docs for IComparer interface.

Or

Use SortedList class if your key value is string
--
Vadym Stetsyak aka Vadmyst
http://vadmyst.blogspot.com

"MikeY" <mi*******@yaho.com> wrote in message
news:dX********************@news20.bellglobal.com. ..
Hi Eveyone,

I'm trying to sort my ArrayList, but I'm getting stumped. Hopefully
someone can help me out. I'm using C# Windows forms, but Console app for
testing.
What I am doing is pulling my data from my database and putting the data
into an ArrayList. from there I want to be able to sort the data out. This
is where I"m getting stumped. Getting at, and viewing the data is all good
until I try to use "myArrayList.Sort". Trying various sort methods pull
errors ie: "Specified IComparer threw an exception". As for me data I
won't know the amount of data that there will be in the database, just
that I want to sort the first row of my arraylist. A sample of my code
follows. Txs in advance and Any and all help is appreciated.

using System;
using System.Collections;
using System.Data.OleDb;

namespace Ch11Ex01_ArrayList
{
class Class1
{
static void Main(string[] args)
{
try
{ //Connetion to DataBase
OleDbConnection myConnection = new OleDbConnection(@"Provider =
Microsoft.Jet.OLEDB.4.0;Data Source = C:\Host.mdb");
//Open Connection to DataBase
myConnection.Open();
//SQL Command for myConnection
OleDbCommand myCommand = myConnection.CreateCommand();
//Initialize SQL SELECT command to retrieve data
myCommand.CommandText = "SELECT * FROM Food_Lunch_Menu";
//Create DataReader
OleDbDataReader myDataReader = myCommand.ExecuteReader();

ArrayList myArrayList = new ArrayList();

while(myDataReader.Read())
{
myName myItem = new myName(myDataReader["Index"].ToString());
myItem.myIndex(myDataReader["Name"].ToString());
myArrayList.Add(myItem);
Console.WriteLine(myItem.Name + " " + myItem.Index);
}

myArrayList.Sort(0, 0, null); <-Problem Spot

foreach(myClass myItems in myArrayList)
{
Console.WriteLine(myItems.Name + " " + myItems.Index);
}
myDataReader.Close();
myConnection.Close();
}
catch(Exception myException)
{
Console.WriteLine(myException.Message);
}
}
}
}

Jan 26 '06 #3
Firstly, you are sorting 0 records starting at 0, so it isn't going to sort
anything (the 0,0 in the call)

Secondly, you are asking it to use the default IComparable definition: fine,
but this is the one bit of code you haven't included - i.e. MyClass

I would *expect* (from your code; I'm not saying it is perfect) something
like:

public class MyClass : IComparable
{
public readonly string Name; // readonly field as cheap demo solution
private string index;
public string Index {get {return index;}}
public MyClass(string name)
{
Name = name;
}
public void myIndex(string index) {
this.index = index;
}
public int CompareTo(object obj)
{
MyClass second = obj as MyClass;
int result = Index.CompareTo(second.Index);
if(result==0) result = Name.CompareTo(second.Name);
return result;
}
}

This has a CompareTo method that should sort by Index then Name;

Other points; you should probably sort *after* you have closed the
connection etc
Index should have a getter and setter rather than myIndex(string index)

Does that shine any light?

Marc
Jan 26 '06 #4
> Firstly, you are sorting 0 records starting at 0, so it isn't going to
sort anything (the 0,0 in the call)

Secondly, you are asking it to use the default IComparable definition:
fine, but this is the one bit of code you haven't included - i.e.
MyClass

I would *expect* (from your code; I'm not saying it is perfect)
something like:

public class MyClass : IComparable
{
public readonly string Name; // readonly field as cheap demo
solution
private string index;
public string Index {get {return index;}}
public MyClass(string name)
{
Name = name;
}
public void myIndex(string index) {
this.index = index;
}
public int CompareTo(object obj)
{
MyClass second = obj as MyClass;
int result = Index.CompareTo(second.Index);
if(result==0) result = Name.CompareTo(second.Name);
return result;
}
}
This has a CompareTo method that should sort by Index then Name;

Other points; you should probably sort *after* you have closed the
connection etc
Index should have a getter and setter rather than myIndex(string
index)
Does that shine any light?

Marc


All good points Marc.

For the record, I would opt for creating a seperate IComparer for the sole
reason of sticking to the single responsibility rule. Other than that, implementing
IComparable on MyName works the same way.

Chris
Jan 26 '06 #5
Thank you all very much Chris & Marc works like a charm.

MikeY
"MikeY" <mi*******@yaho.com> wrote in message
news:dX********************@news20.bellglobal.com. ..
Hi Eveyone,

I'm trying to sort my ArrayList, but I'm getting stumped. Hopefully
someone can help me out. I'm using C# Windows forms, but Console app for
testing.
What I am doing is pulling my data from my database and putting the data
into an ArrayList. from there I want to be able to sort the data out. This
is where I"m getting stumped. Getting at, and viewing the data is all good
until I try to use "myArrayList.Sort". Trying various sort methods pull
errors ie: "Specified IComparer threw an exception". As for me data I
won't know the amount of data that there will be in the database, just
that I want to sort the first row of my arraylist. A sample of my code
follows. Txs in advance and Any and all help is appreciated.

using System;
using System.Collections;
using System.Data.OleDb;

namespace Ch11Ex01_ArrayList
{
class Class1
{
static void Main(string[] args)
{
try
{ //Connetion to DataBase
OleDbConnection myConnection = new OleDbConnection(@"Provider =
Microsoft.Jet.OLEDB.4.0;Data Source = C:\Host.mdb");
//Open Connection to DataBase
myConnection.Open();
//SQL Command for myConnection
OleDbCommand myCommand = myConnection.CreateCommand();
//Initialize SQL SELECT command to retrieve data
myCommand.CommandText = "SELECT * FROM Food_Lunch_Menu";
//Create DataReader
OleDbDataReader myDataReader = myCommand.ExecuteReader();

ArrayList myArrayList = new ArrayList();

while(myDataReader.Read())
{
myName myItem = new myName(myDataReader["Index"].ToString());
myItem.myIndex(myDataReader["Name"].ToString());
myArrayList.Add(myItem);
Console.WriteLine(myItem.Name + " " + myItem.Index);
}

myArrayList.Sort(0, 0, null); <-Problem Spot

foreach(myClass myItems in myArrayList)
{
Console.WriteLine(myItems.Name + " " + myItems.Index);
}
myDataReader.Close();
myConnection.Close();
}
catch(Exception myException)
{
Console.WriteLine(myException.Message);
}
}
}
}

Jan 26 '06 #6

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by SASRS | last post: by
1 post views Thread by Sargas Atum | last post: by
reply views Thread by Eph0nk | last post: by
4 posts views Thread by Niels | last post: by
5 posts views Thread by drdave | last post: by
2 posts views Thread by iKiLL | last post: by
reply views Thread by MichaelMortimer | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.