473,791 Members | 3,360 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(Glob al.Games);

I get an error message:

Argument '1': cannot convert from 'ChatMark1.Game HashTable' to 'int'

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

Nov 17 '05 #1
9 4039
Oberon <Ob****@solstic e.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(Glob al.Games);

I get an error message:

Argument '1': cannot convert from 'ChatMark1.Game HashTable' to 'int'

But the SortedList constructor is overloaded and one parameter it
accepts is an object of type Systems.Collect ion.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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
Oberon <Ob****@solstic e.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(Glob al.Games);

I get an error message:

Argument '1': cannot convert from 'ChatMark1.Game HashTable' to 'int'

But the SortedList constructor is overloaded and one parameter it
accepts is an object of type Systems.Collect ion.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.co m>
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.co m> wrote:
Oberon <Ob****@solstic e.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(Glob al.Games);

I get an error message:

Argument '1': cannot convert from 'ChatMark1.Game HashTable' to 'int'

But the SortedList constructor is overloaded and one parameter it
accepts is an object of type Systems.Collect ion.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(Glob al.Games);

with the error messages:

Argument '1': cannot convert from 'SortHash.GameH ashTable' to
'int'
The best overloaded method match for
'System.Collect ions.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="Def ault.aspx.cs"
AutoEventWireup ="false" Inherits="SortH ash._Default1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Defaul t</title>
<meta content="Micros oft Visual Studio .NET 7.1" name="GENERATOR ">
<meta content="C#" name="CODE_LANG UAGE">
<meta content="JavaSc ript" name="vs_defaul tClientScript">
<meta content="http://schemas.microso ft.com/intellisense/ie5"
name="vs_target Schema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="dgGames" runat="server"
AutoGenerateCol umns="False" EnableViewState ="False"
AllowSorting="T rue" OnSortCommand=" SortRows">
<Columns>
<asp:BoundColum n DataField="Titl e" HeaderText="Tit le"
SortExpression= "Title"></asp:BoundColumn >
<asp:BoundColum n DataField="Play Time" HeaderText="Day "
DataFormatStrin g="{0:ddd}"></asp:BoundColumn >
<asp:BoundColum n DataField="Play Time" HeaderText="Tim e"
DataFormatStrin g="{0:HH':'mm': ' 'GMT'}"></asp:BoundColumn >
<asp:BoundColum n DataField="Play Time" HeaderText="Sta rt"
SortExpression= "Start" DataFormatStrin g="{0:m}"></asp:BoundColumn >
<asp:TemplateCo lumn HeaderText="Rec ruiting">
<ItemTemplate >
<asp:CheckBox id="chkRecruiti ng" runat="server"
Checked='<%# DataBinder.Eval (Container, "DataItem.Recru iting") %>'
disabled />
</ItemTemplate>
</asp:TemplateCol umn>
</Columns>
</asp:DataGrid></form>
</body>
</HTML>

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

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace SortHash
{
public class _Default1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Data Grid dgGames;

private void Page_Load(objec t sender, System.EventArg s e)
{
dgGames.DataSou rce = Global.Games;
dgGames.DataBin d();
}

public void SortRows(object sender, DataGridSortCom mandEventArgs
e)
{
SortedList sortedGames = new SortedList(Glob al.Games);
dgGames.DataSou rce = Global.Games;
dgGames.DataBin d();
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
InitializeCompo nent();
base.OnInit(e);
}

private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

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

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

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

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

public Game(
int initialGameID,
string initialTitle,
bool initialRecruiti ng,
DateTime initialPlayTime )
{
GameID = initialGameID;
Title = initialTitle;
Recruiting = initialRecruiti ng;
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.Collecti ons;
using System.Componen tModel;
using System.Data.Sql Client;
using System.Web;
using System.Web.Sess ionState;

namespace SortHash
{
public class Global : System.Web.Http Application
{
public static string gameConnection = "packet size=4096;user
id=ape;pwd=monk ey;data source=ASROCK;p ersist security
info=False;init ial catalog=ChatMar k1";
public static GameHashTable games;
private System.Componen tModel.IContain er components = null;

public Global()
{
InitializeCompo nent();
}

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

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

public static void GameLoad()
{
SqlConnection connGames = new SqlConnection(g ameConnection);
connGames.Open( );
SqlCommand cmd = new SqlCommand("SEL ECT gameID, title,
recruiting, playTime FROM Games", connGames);
SqlDataReader reader;
reader = cmd.ExecuteRead er();

Game game;
games = new GameHashTable() ;
while (reader.Read())
{
game = new Game(
reader.GetInt32 (0),
reader.GetStrin g(1),
reader.GetBoole an(2),
reader.GetDateT ime(3));
games.Add(game) ;
}
reader.Close();
connGames.Close ();
}

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

#region Web Form Designer generated code
private void InitializeCompo nent()
{
this.components = new System.Componen tModel.Containe r();
}
#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_recrui ting DEFAULT
(1),
playTime datetime NOT NULL CONSTRAINT DF_Games_playTi me DEFAULT
(getdate()),
CONSTRAINT PK_Games PRIMARY KEY CLUSTERED (gameID) ON PRIMARY
)

Nov 17 '05 #4
Oberon <Ob****@solstic e.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.Collecti ons;

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(IDic tionary) 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.co m>
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.co m> wrote:
Oberon <Ob****@solstic e.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.Collecti ons;

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(IDic tionary) 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/frlrfsystemcoll ectionshashtabl eclasstopic.asp >

Nov 17 '05 #6

"Oberon" wrote:
On Fri, 20 May 2005 17:41:12 +0100, Jon Skeet [C# MVP]
<sk***@pobox.co m> 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(Glob al.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****@solstic e.com> wrote:
The problem is that your GameHashTable isn't an IDictionary, so it
certainly can't use the SortedList(IDic tionary) 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.co m>
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.co m> wrote:
Oberon <Ob****@solstic e.com> wrote:
>The problem is that your GameHashTable isn't an IDictionary, so it
>certainly can't use the SortedList(IDic tionary) 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****@solstic e.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.co m>
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
20317
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? Thanks! -Mark IDictionaryEnumerator myEnumerator = myHashTable.GetEnumerator(); while ( myEnumerator.MoveNext() ) { //Please print ordered by Key ... Response.Write("<BR>" + myEnumerator.Key.ToString() + ", " + myEnumerator.Value.ToString())
5
7731
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 for me? Thanks!
9
2262
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 aPerson.birthdate.
5
2832
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 like it to return an XML serialized version of an object.
0
235
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 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:
4
2200
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
2467
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 Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here
4
1544
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 create a new row in the DataGrid and set the date to me within the current sort range, the newly created row "jumps" to its correct position in the grid. This obviously makes sense because it is following the sort rule.
2
1515
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
10207
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10156
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9997
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.