473,395 Members | 1,937 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

How can I sort a HashTable by a specified column?

My HashTable (Global.Games) is a static collection of objects of type
Game. A Game object has 8 fields (exposed as properties). The key to
the HashTable is also one of these fields (GameID, of type int).

When I try to create a SortedList from the HashTable with the
following:

SortedList sortedGames = new SortedList(Global.Games);

I get an error message:

Argument '1': cannot convert from 'ChatMark1.GameHashTable' to 'int'

But the SortedList constructor is overloaded and one parameter it
accepts is an object of type Systems.Collection.IDictionary. Why does
it now expect the Global.Games to be of type 'int'?

Nov 17 '05 #1
9 4008
Oberon <Ob****@solstice.com> wrote:
My HashTable (Global.Games) is a static collection of objects of type
Game. A Game object has 8 fields (exposed as properties). The key to
the HashTable is also one of these fields (GameID, of type int).

When I try to create a SortedList from the HashTable with the
following:

SortedList sortedGames = new SortedList(Global.Games);

I get an error message:

Argument '1': cannot convert from 'ChatMark1.GameHashTable' to 'int'

But the SortedList constructor is overloaded and one parameter it
accepts is an object of type Systems.Collection.IDictionary. Why does
it now expect the Global.Games to be of type 'int'?


Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
Oberon <Ob****@solstice.com> wrote:
My HashTable (Global.Games) is a static collection of objects of type
Game. A Game object has 8 fields (exposed as properties). The key to
the HashTable is also one of these fields (GameID, of type int).

When I try to create a SortedList from the HashTable with the
following:

SortedList sortedGames = new SortedList(Global.Games);

I get an error message:

Argument '1': cannot convert from 'ChatMark1.GameHashTable' to 'int'

But the SortedList constructor is overloaded and one parameter it
accepts is an object of type Systems.Collection.IDictionary. Why does
it now expect the Global.Games to be of type 'int'?


Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
On Fri, 20 May 2005 06:50:33 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
Oberon <Ob****@solstice.com> wrote:
My HashTable (Global.Games) is a static collection of objects of type
Game. A Game object has 8 fields (exposed as properties). The key to
the HashTable is also one of these fields (GameID, of type int).

When I try to create a SortedList from the HashTable with the
following:

SortedList sortedGames = new SortedList(Global.Games);

I get an error message:

Argument '1': cannot convert from 'ChatMark1.GameHashTable' to 'int'

But the SortedList constructor is overloaded and one parameter it
accepts is an object of type Systems.Collection.IDictionary. Why does
it now expect the Global.Games to be of type 'int'?


Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.


I can't do that. I have to post two complete pages. This is the
'simplified' code for the problem, below.

The program fails on this line:

SortedList sortedGames = new SortedList(Global.Games);

with the error messages:

Argument '1': cannot convert from 'SortHash.GameHashTable' to
'int'
The best overloaded method match for
'System.Collections.SortedList.SortedList(int)' has some invalid
arguments
Could not find any attribute 'disabled' of element 'CheckBox'.

(The 3rd (other) error message is not important since the program
works even if the offending disabled attribute is left in the code
when the line creating the SortedList is commentated out.

I can see what I'm doing wrong now. I'm giving the wrong parameters to
the new SortedList. The problem is that I don't actually understand
what parameters it will take here. I was using an example from some
book code, but perhaps the constructors for the sorted list have
changed since then?, or maybe the code only works with a simple
HashTable, not my more complex one?

Would I be better off leaving the HashTable out completely and just
putting my recordset in the Application Cache? I think so. That is
what I will try to do to solve the problem as I'm probably out of my
depth here.
+ + + + + + + + + + + + + + + + + + + + +
Here is my web page.
+ + + + + + + + + + + + + + + + + + + + +
<%@ Page language="c#" Codebehind="Default.aspx.cs"
AutoEventWireup="false" Inherits="SortHash._Default1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Default</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="dgGames" runat="server"
AutoGenerateColumns="False" EnableViewState="False"
AllowSorting="True" OnSortCommand="SortRows">
<Columns>
<asp:BoundColumn DataField="Title" HeaderText="Title"
SortExpression="Title"></asp:BoundColumn>
<asp:BoundColumn DataField="PlayTime" HeaderText="Day"
DataFormatString="{0:ddd}"></asp:BoundColumn>
<asp:BoundColumn DataField="PlayTime" HeaderText="Time"
DataFormatString="{0:HH':'mm':' 'GMT'}"></asp:BoundColumn>
<asp:BoundColumn DataField="PlayTime" HeaderText="Start"
SortExpression="Start" DataFormatString="{0:m}"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Recruiting">
<ItemTemplate>
<asp:CheckBox id="chkRecruiting" runat="server"
Checked='<%# DataBinder.Eval(Container, "DataItem.Recruiting") %>'
disabled />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid></form>
</body>
</HTML>

+ + + + + + + + + + + + + + + + + + + + +
Here is the code behind for the above page:
+ + + + + + + + + + + + + + + + + + + + +

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace SortHash
{
public class _Default1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgGames;

private void Page_Load(object sender, System.EventArgs e)
{
dgGames.DataSource = Global.Games;
dgGames.DataBind();
}

public void SortRows(object sender, DataGridSortCommandEventArgs
e)
{
SortedList sortedGames = new SortedList(Global.Games);
dgGames.DataSource = Global.Games;
dgGames.DataBind();
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
public class GameHashTable : IEnumerable
{
Hashtable _games;

public GameHashTable()
{
_games = new Hashtable();
}
public IEnumerator GetEnumerator()
{
return _games.Values.GetEnumerator();
}
public Game this[int GameID]
{
get {return (Game) _games[GameID];}
set {Add(value);}
}
public void Add(Game Item)
{
if (Item == null)
throw new ArgumentException("Game can not be null");
_games.Add(Item.GameID, Item);

}
public void Remove(Game Item)
{
_games.Remove(Item.GameID);
}
}

public class Game
{
private int _gameID;
private string _title;
private bool _recruiting;
private DateTime _playTime;

public Game(
int initialGameID,
string initialTitle,
bool initialRecruiting,
DateTime initialPlayTime)
{
GameID = initialGameID;
Title = initialTitle;
Recruiting = initialRecruiting;
PlayTime = initialPlayTime;
}

public int GameID
{
get { return _gameID; }
set {_gameID = value;}
}
public string Title
{
get {return _title;}
set {_title = value;}
}
public bool Recruiting
{
get {return _recruiting;}
set {_recruiting = value;}
}
public DateTime PlayTime
{
get {return _playTime;}
set {_playTime = value;}
}
}
}
+ + + + + + + + + + + + + + + + + + + + +
Here is my Global.asax
+ + + + + + + + + + + + + + + + + + + + +
using System;
using System.Collections;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;

namespace SortHash
{
public class Global : System.Web.HttpApplication
{
public static string gameConnection = "packet size=4096;user
id=ape;pwd=monkey;data source=ASROCK;persist security
info=False;initial catalog=ChatMark1";
public static GameHashTable games;
private System.ComponentModel.IContainer components = null;

public Global()
{
InitializeComponent();
}

protected void Application_Start(Object sender, EventArgs e)
{
Global.GameLoad();
}

public static string GameConnection
{ get { return gameConnection;} }

public static void GameLoad()
{
SqlConnection connGames = new SqlConnection(gameConnection);
connGames.Open();
SqlCommand cmd = new SqlCommand("SELECT gameID, title,
recruiting, playTime FROM Games", connGames);
SqlDataReader reader;
reader = cmd.ExecuteReader();

Game game;
games = new GameHashTable();
while (reader.Read())
{
game = new Game(
reader.GetInt32(0),
reader.GetString(1),
reader.GetBoolean(2),
reader.GetDateTime(3));
games.Add(game);
}
reader.Close();
connGames.Close();
}

public static GameHashTable Games
{
get { return games; }
}

#region Web Form Designer generated code
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
}
#endregion
}
}

+ + + + + + + + + + + + + + + + + + + + +
Last. My database table:
+ + + + + + + + + + + + + + + + + + + + +

CREATE TABLE Games (
gameID int IDENTITY (1, 1) NOT NULL ,
title varchar (50) NOT NULL ,
recruiting bit NOT NULL CONSTRAINT DF_Games_recruiting DEFAULT
(1),
playTime datetime NOT NULL CONSTRAINT DF_Games_playTime DEFAULT
(getdate()),
CONSTRAINT PK_Games PRIMARY KEY CLUSTERED (gameID) ON PRIMARY
)

Nov 17 '05 #4
Oberon <Ob****@solstice.com> wrote:
See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
I can't do that. I have to post two complete pages.


No, you don't. Here's a short but complete program which shows exactly
what's going wrong, without any ASP.NET at all:

using System;
using System.Collections;

public class Test
{
static void Main()
{
GameHashTable hash = new GameHashTable();
new SortedList(hash);
}
}

public class GameHashTable : IEnumerable
{
public IEnumerator GetEnumerator()
{
return null;
}
}

The problem is that your GameHashTable isn't an IDictionary, so it
certainly can't use the SortedList(IDictionary) constructor.
I can see what I'm doing wrong now. I'm giving the wrong parameters to
the new SortedList. The problem is that I don't actually understand
what parameters it will take here.
Exactly the documented ones.
I was using an example from some
book code, but perhaps the constructors for the sorted list have
changed since then?, or maybe the code only works with a simple
HashTable, not my more complex one?


No, it works with anything which implements IDictionary - which your
class doesn't.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
On Fri, 20 May 2005 17:41:12 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
Oberon <Ob****@solstice.com> wrote:
>See http://www.pobox.com/~skeet/csharp/complete.html for details of
>what I mean by that.


I can't do that. I have to post two complete pages.


No, you don't. Here's a short but complete program which shows exactly
what's going wrong, without any ASP.NET at all:

using System;
using System.Collections;

public class Test
{
static void Main()
{
GameHashTable hash = new GameHashTable();
new SortedList(hash);
}
}

public class GameHashTable : IEnumerable
{
public IEnumerator GetEnumerator()
{
return null;
}
}

The problem is that your GameHashTable isn't an IDictionary, so it
certainly can't use the SortedList(IDictionary) constructor.


I've given up on the idea of using a HashTable to do this job and will
use a DataSet inserted into the Cache instead; which is what 99% of
people would do when faced with a similar problem to mine.
I can see what I'm doing wrong now. I'm giving the wrong parameters to
the new SortedList. The problem is that I don't actually understand
what parameters it will take here.


Exactly the documented ones.
I was using an example from some
book code, but perhaps the constructors for the sorted list have
changed since then?, or maybe the code only works with a simple
HashTable, not my more complex one?


No, it works with anything which implements IDictionary - which your
class doesn't.


But the documentation says that a HashTable does implement
IDictionary:

<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcollectionshashtableclasstopic.asp>

Nov 17 '05 #6

"Oberon" wrote:
On Fri, 20 May 2005 17:41:12 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:


<snip>
No, it works with anything which implements IDictionary - which your
class doesn't.


But the documentation says that a Hashtable does implement
IDictionary:


But you're not passing a Hashtable object to a SortedList.

public class GameHashTable : IEnumerable
{
Hashtable _games;

// ...
}

The GameHashTable class contains a Hashtable, but doesn't implement the
IDictionary interface. It's not the same thing. So when you pass an
instance of the GameHashTable:

SortedList sortedGames = new SortedList(Global.Games);

You get an error.

Global.Games is an instance of the GameHashTable class, not an instance
of the Hashtable class.

Nov 17 '05 #7
Oberon <Ob****@solstice.com> wrote:
The problem is that your GameHashTable isn't an IDictionary, so it
certainly can't use the SortedList(IDictionary) constructor.


I've given up on the idea of using a HashTable to do this job and will
use a DataSet inserted into the Cache instead; which is what 99% of
people would do when faced with a similar problem to mine.


Well, without knowing more about it, I couldn't say for sure.
Personally I'd usually prefer a Hashtable to a DataSet just for
simplicity.
No, it works with anything which implements IDictionary - which your
class doesn't.


But the documentation says that a HashTable does implement
IDictionary:


Absolutely. And that would be fine if your class derived from
HashTable, but it doesn't. Here's the declaration of your class:

public class GameHashTable : IEnumerable

Nothing about HashTable in there.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
On Sat, 21 May 2005 10:24:40 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
Oberon <Ob****@solstice.com> wrote:
>The problem is that your GameHashTable isn't an IDictionary, so it
>certainly can't use the SortedList(IDictionary) constructor.


I've given up on the idea of using a HashTable to do this job and will
use a DataSet inserted into the Cache instead; which is what 99% of
people would do when faced with a similar problem to mine.


Well, without knowing more about it, I couldn't say for sure.
Personally I'd usually prefer a Hashtable to a DataSet just for
simplicity.
>No, it works with anything which implements IDictionary - which your
>class doesn't.


But the documentation says that a HashTable does implement
IDictionary:


Absolutely. And that would be fine if your class derived from
HashTable, but it doesn't. Here's the declaration of your class:

public class GameHashTable : IEnumerable

Nothing about HashTable in there.


Thanks for all that. I see I need to study more. I'll use DataSets
until I get the hang of this.

Nov 17 '05 #9
Oberon <Ob****@solstice.com> wrote:
Thanks for all that. I see I need to study more. I'll use DataSets
until I get the hang of this.


I wouldn't - DataSets are more complicated than HashTables, and if
you're having trouble understanding the problem, I think you should
really look at the language basics again. I always think it's worth
spending more time getting the basics right rather than ploughing
regardless into more complicated things where you're likely to get
stuck.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Mark | last post by:
I'm using an enumerator to iterate through a HashTable that contains all numeric keys. I'd like to iterarate through the HashTable based on the ordered keys. Is there a quick way to do this?...
5
by: Arjen | last post by:
Hello, Let's say that we have a hashtable with some person objects. This persons have a name. Now I want to sort the people objects inside the hashtable by name. How can the hashtable do this...
9
by: Arjen | last post by:
Hello, Persons is a hashtable which I convert to an array. Person aPerson = new Person; Persons.Values.CopyTo( aPerson, 0 ); Now I can access the person items like aPerson.name or...
5
by: francois | last post by:
First of all I would to to apologize for resending this post again but I feel like my last post as been spoiled Here I go for my problem: Hi, I have a webservice that I am using and I would...
0
by: Oberon | last post by:
My HashTable (Global.Games) is a static collection of objects of type Game. A Game object has 8 fields (exposed as properties). The key to the HashTable is also one of these fields (GameID, of type...
4
by: Arjen | last post by:
Hi, I need to add this inside an array: 1 3 2 4 3 2 4 5 5 1 I think of using this:
7
by: DC Gringo | last post by:
I have a datagrid that won't sort. The event handler is firing and return label text, just not the sort. Here's my Sub Page_Load and Sub DataGrid1_SortCommand: -------------------- Private...
4
by: G .Net | last post by:
Hi I have a question which I hope you can help with. I am setting the DataSource of a DataGrid to be a DataView. I am sorting the DataView by various fields which include a Date. When I...
2
by: Dimon | last post by:
Hi there, I need to sort multi-dimensional array by two columns. I.e. I have the following: a b c ----------- 1 12 1 0 10 2 1 10 3 1 15 4 0 14 5
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.