本文介绍了如何按指定列对HashTable进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我的HashTable(Global.Games)是一个静态的对象类型 Game。 Game对象有8个字段(作为属性公开)。 HashTable的关键是HashTable也是其中一个字段(GameID,类型为int)。 当我尝试使用HashTable创建一个SortedList时 以下: SortedList sortedGames = new SortedList(Global.Games); 我收到错误消息: 参数''1':无法从''ChatMark1.GameHashTable''转换为''int'' 但是SortedList构造函数被重载,它接受的一个参数是Systems.Collection.IDictionary类型的对象。为什么 现在期望Global.Games的类型为''int''? 解决方案 Oberon< Ob **** @ solstice.com>写道:我的HashTable(Global.Games)是类型为 Game的对象的静态集合。 Game对象有8个字段(作为属性公开)。 HashTable的关键还在于其中一个字段(GameID,类型为int)。 当我尝试使用从HashTable创建一个SortedList: SortedList sortedGames = new SortedList(Global.Games); 我收到一条错误消息: 参数''1'':无法转换''ChatMark1.GameHashTable''到''int'' 但SortedList构造函数重载,它接受的一个参数是Systems.Collection.IDictionary类型的对象。为什么它现在期望Global.Games是'int'类型? 你能发一个简短但完整的程序来证明 问题? 见 http://www.pobox.com/~skeet/csharp/complete.html 了解详情 我的意思是什么。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复群组,请不要邮寄我也是 Oberon< Ob **** @ solstice.com>写道:我的HashTable(Global.Games)是类型为 Game的对象的静态集合。 Game对象有8个字段(作为属性公开)。 HashTable的关键还在于其中一个字段(GameID,类型为int)。 当我尝试使用从HashTable创建一个SortedList: SortedList sortedGames = new SortedList(Global.Games); 我收到一条错误消息: 参数''1'':无法转换''ChatMark1.GameHashTable''到''int'' 但SortedList构造函数重载,它接受的一个参数是Systems.Collection.IDictionary类型的对象。为什么它现在期望Global.Games是'int'类型? 你能发一个简短但完整的程序来证明 问题? 见 http://www.pobox.com/~skeet/csharp/complete.html 了解详情 我的意思是什么。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复群组,请不要邮寄我也是 2005年5月20日星期五06:50:33 +0100,Jon Skeet [C#MVP] < sk ** *@pobox.com>写道: Oberon< Ob **** @ solstice.com>写道:我的HashTable(Global.Games)是类型为 Game的对象的静态集合。 Game对象有8个字段(作为属性公开)。 HashTable的关键还在于其中一个字段(GameID,类型为int)。 当我尝试使用从HashTable创建一个SortedList: SortedList sortedGames = new SortedList(Global.Games); 我收到一条错误消息: 参数''1'':无法转换''ChatMark1.GameHashTable''到''int'' 但SortedList构造函数重载,它接受的一个参数是Systems.Collection.IDictionary类型的对象。为什么它现在期望Global.Games是'int'类型? 你能发一个简短但完整的程序来演示问题? 请参阅 http:// www.pobox.com/~skeet/csharp/complete.html 了解我的意思。 我可以'那样做。我必须发布两个完整的页面。这是问题的 ''简化''代码,如下所示。 程序在此行上失败: SortedList sortedGames = new SortedList(Global.Games); ,错误消息: 参数''1'' :无法从''SortHash.GameHashTable''转换为 ''int'' 最佳重载方法匹配 ''系统.Collections.SortedList.SortedList(int)''有一些无效的 参数 找不到元素''CheckBox''的任何属性''disabled''。 br /> (第三个(其他)错误消息并不重要,因为程序 即使代码中遗留了违规属性,也会有效。 当创建SortedList的行被注释掉时。 我现在可以看到我做错了什么。我给错了参数 新的SortedList。问题在于我实际上并不了解 这里需要什么参数。我使用了一些 书籍代码中的一个例子,但是排序列表的构造函数可能从那时起改变了?b $ b,或者代码只能用于简单的 HashTable,不是我更复杂的一个吗? 我最好完全离开HashTable并且只需 我的记录集在应用程序缓存中?我认同。那是 我将尝试做什么来解决这个问题,因为我可能已经超出了我的 深度。 + + + + + + + + + + + + + + + + + + + + + + + 这是我的网页。 + + + + + + + + + + + + + + + + + + + + + + <%@ Page language =" c#" Codebehind =" Default.aspx.cs" AutoEventWireup =" false"继承= QUOT; SortHash._Default1" %> <!DOCTYPE HTML PUBLIC" - // W3C // DTD HTML 4.0 Transitional // EN" > < HTML> < HEAD> < title>默认< / 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"方法= QUOT;交" 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 =" ;游戏时间与QUOT; 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")%>'' 禁用/ > < / ItemTemplate> < / asp:TemplateColumn> < / Columns> < / asp:DataGrid>< / form> < / body> < / HTML> + + + + + + + + + + + + + + + + + + + + + + 以上是上面的代码: + + + + + + + + + + + + + + + + + + + + + + 使用System; 使用System.Collections; 使用System.ComponentModel; 使用System.Data; 使用System.Drawing; 使用System.Web; 使用System.Web.SessionState; 使用System.Web.UI; 使用System.Web.UI.WebControls; 使用System.Web.UI.HtmlControls; 命名空间SortHash { 公共类_De fault1: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(对象发送者,DataGridSortCommandEventArgs e) { SortedList sortedGames = new SortedList(Global.Games); dgGames.DataSource = Global.Games; dgGames.DataBind(); } #region Web窗体设计器生成的代码 覆盖protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Load + = new System.EventHandler(this.Page_Load); } #endregion } 公共类GameHashTable:IEnumerable { Hashtable _games; 公共GameHashTable() { _games = new Hashtable( ); } public IEnumerator GetEnumerator() { return _games.Values.GetEnumerator(); } public game this [int GameID] { get {return(Game)_games [GameID ];} 设置{添加(值);} } public void添加(游戏物品) { if(Item == null) 抛出新的ArgumentException(游戏不能为空); _games.Add (Item.GameID,Item); } public void删除(游戏物品) { _games.Remove(Item.GameID); } } 公共课游戏 { private int _gameID; private string _title; private bool _recruiting; private DateTime _playTime; 公共游戏( int initialGameID, string initialTitle, bool initialRecruiting, DateTime initialPlayTime) { GameID = initialGameID; Title = initialTitle; Recruiting = initialRecruiting; PlayTime = initialPlayTime; } public int GameID { get {return _gameID; } 设置{_gameID = value;} } 公共字符串标题 { get {return _title;} set {_title = value;} } public bool Recruiting { get {return _recruiting;} set {_recruiting = value;} } public DateTime PlayTime { get {return _playTime;} set {_ playTime = value;} } } } + + + + + + + + + + + + + + + + + + + + + + 这是我的Global.asax + + + + + + + + + + + + + + + + + + + + + 使用系统; 使用System.Collections; 使用System.ComponentModel; 使用System.Data.SqlClient; 使用System.Web; 使用System.Web.SessionState; 命名空间SortHash { 公共类Global:System.Web.HttpApplication { public s tatic string gameConnection =" packet size = 4096; user id = ape; pwd = monkey; data source = ASROCK; persist security info = False; initial catalog = ChatMark1" ;; public static GameHashTable游戏; private System.ComponentModel.IContainer components = null; public Global() { InitializeComponent(); } protected void Application_Start(Object sender,EventArgs e) { Global.GameLoad(); } 公共静态字符串GameConnection {get {return gameConnection;}} public static void GameLoad() { SqlConnection connGames = new SqlConnection(gameConnection); connGames.Open(); SqlCommand cmd = new SqlCommand(" SELECT gameID,title, 招募,playTime FROM Games",connGames); SqlDataReader reader; reader = cmd.ExecuteReader(); 游戏; games = new GameHashTable(); while(reader.Read()) { 游戏=新游戏( reader.GetInt32(0), reader.GetString(1), reader.GetBoolean(2), reader.GetDateTime(3)); games.Add(game); } reader.Close(); connGames.Close(); } public static GameHashTable游戏 { 获得{返回游戏; } } #region Web窗体设计器生成的代码 private void InitializeComponent() { this.components = new System.ComponentModel.Container(); } #endregion } } + + + + + + + + + + + + + + + + + + + + + + + 持续。我的数据库表: + + + + + + + + + + + + + + + + + + + + + + CREATE TABLE游戏( gameID int IDENTITY(1,1)NOT NULL, title varchar(50)NOT NULL, 招募位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 ) My HashTable (Global.Games) is a static collection of objects of typeGame. A Game object has 8 fields (exposed as properties). The key tothe HashTable is also one of these fields (GameID, of type int).When I try to create a SortedList from the HashTable with thefollowing: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 itaccepts is an object of type Systems.Collection.IDictionary. Why doesit now expect the Global.Games to be of type ''int''? 解决方案 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 theproblem?See http://www.pobox.com/~skeet/csharp/complete.html for details ofwhat I mean by that.--Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me tooOberon <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 theproblem?See http://www.pobox.com/~skeet/csharp/complete.html for details ofwhat I mean by that.--Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me tooOn 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 theproblem?See http://www.pobox.com/~skeet/csharp/complete.html for details ofwhat 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 invalidargumentsCould not find any attribute ''disabled'' of element ''CheckBox''.(The 3rd (other) error message is not important since the programworks even if the offending disabled attribute is left in the codewhen the line creating the SortedList is commentated out.I can see what I''m doing wrong now. I''m giving the wrong parameters tothe new SortedList. The problem is that I don''t actually understandwhat parameters it will take here. I was using an example from somebook code, but perhaps the constructors for the sorted list havechanged since then?, or maybe the code only works with a simpleHashTable, not my more complex one?Would I be better off leaving the HashTable out completely and justputting my recordset in the Application Cache? I think so. That iswhat I will try to do to solve the problem as I''m probably out of mydepth 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, DataGridSortCommandEventArgse){SortedList sortedGames = new SortedList(Global.Games);dgGames.DataSource = Global.Games;dgGames.DataBind();}#region Web Form Designer generated codeoverride 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;userid=ape;pwd=monkey;data source=ASROCK;persist securityinfo=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 codeprivate 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) 这篇关于如何按指定列对HashTable进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-21 12:00