哈 希 表 的 操 作

  1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7    
  8
  9namespace 哈希表
 10{
 11    /// <summary>
 12    /// Form1 的摘要说明。
 13    /// </summary>

 14    public class Form1 : System.Windows.Forms.Form
 15    {
 16        private System.Windows.Forms.Button button1;
 17        private System.Windows.Forms.RichTextBox richTextBox1;
 18        /// <summary>
 19        /// 必需的设计器变量。
 20        /// </summary>

 21        private System.ComponentModel.Container components = null;
 22
 23        public Form1()
 24        {
 25            //
 26            // Windows 窗体设计器支持所必需的
 27            //
 28            InitializeComponent();
 29
 30            //
 31            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 32            //
 33        }

 34
 35        /// <summary>
 36        /// 清理所有正在使用的资源。
 37        /// </summary>

 38        protected override void Dispose( bool disposing )
 39        {
 40            if( disposing )
 41            {
 42                if (components != null
 43                {
 44                    components.Dispose();
 45                }

 46            }

 47            base.Dispose( disposing );
 48        }

 49
 50        Windows 窗体设计器生成的代码
 90
 91        /// <summary>
 92        /// 应用程序的主入口点。
 93        /// </summary>

 94        [STAThread]
 95        static void Main() 
 96        {
 97            Application.Run(new Form1());
 98        }

 99
100//        每个元素是一个存储在 DictionaryEntry 对象中的键/值对。键不能为空引用(Visual Basic 中为 Nothing),但值可以。
101//
102//        用作 Hashtable 中的键的对象必须实现或继承 Object.GetHashCode 和 Object.Equals 方法。如果键相等性只是引用相等性,这些方法的继承实现将满足需要。此外,如果该键存在于 Hashtable 中,那么当使用相同参数调用这些方法时,这些方法必须生成相同的结果。只要键对象用作 Hashtable 中的键,它们就必须是永远不变的。
103//
104//        当把某个元素添加到 Hashtable 时,将根据键的哈希代码将该元素放入存储桶中。该键的后续查找将使用键的哈希代码只在一个特定存储桶中搜索,这将大大减少为查找一个元素所需的键比较的次数。
105//
106//        Hashtable 的加载因子确定元素与存储桶的最大比率。加载因子越小,平均查找速度越快,但消耗的内存也增加。默认的加载因子 1.0 通常提供速度和大小之间的最佳平衡。当创建 Hashtable 时,也可以指定其他加载因子。
107//
108//        当向 Hashtable 添加元素时,Hashtable 的实际加载因子将增加。当实际加载因子达到此加载因子时,Hashtable 中存储桶的数目自动增加到大于当前 Hashtable 存储桶数两倍的最小质数。
109//
110//        Hashtable 中的每个键对象必须提供其自己的哈希函数,可通过调用 GetHash 访问该函数。但是,可将任何实现 IHashCodeProvider 的对象传递到 Hashtable 构造函数,而且该哈希函数用于该表中的所有对象。
111
112       
113 
114        private void button1_Click(object sender, System.EventArgs e)
115        {
116
117            //为哈希表增加值
118            this.richTextBox1.Text =""
119            // Creates and initializes a new Hashtable.
120            Hashtable myHT = new Hashtable();
121            for(int j=0;j<20;j++)
122            myHT.Add("frj"+ j.ToString() ,j ); //注意如果第二个参数采用非数值型将不能用于后面的数据加运算(Dchart.Data  =myHT).
123
124            // Displays the properties and values of the Hashtable.
125            this.richTextBox1.Text += ( "我的哈希表:" )+"\n";
126            this.richTextBox1.Text +="  Count:    "+ myHT.Count.ToString()+"\n"  );
127            this.richTextBox1.Text +="\tKeys and Values:\n" );
128            PrintKeysAndValues( myHT );
129
130            //将哈希表转为一维键/值对数组
131            //这样将方便直接引用
132             
133            this.richTextBox1.Text +="将哈希表转换所得: \n";
134
135            DrawPieChart Dchart=new DrawPieChart(); 
136            
137            Dchart.Data  =myHT;
138       
139            for (int i=1;i<Dchart.data.Length ;i++)
140                this.richTextBox1.Text +=("\t" +Dchart.data.Keys[i].ToString()+"\t" +Dchart.data.Values[i].ToString()+"\n" );
141            
142
143            this.richTextBox1.Text +="取第 6 个数: "+ Dchart.data.Values[6].ToString()+"\n"+"各数总和 : "+Dchart.data.TotalValue.ToString()    ;   
144
145
146        }

147
148        
149
150            public  void PrintKeysAndValues( Hashtable myList )  
151            {
152                IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
153                this.richTextBox1.Text +="\t-KEY-\t-VALUE-\n" );
154                while ( myEnumerator.MoveNext() )
155                    this.richTextBox1.Text +=("\t" +myEnumerator.Key.ToString()+"\t" + myEnumerator.Value.ToString()+"\n" );
156                this.richTextBox1.Text+="另一种遍历方法\n" ; 
157                 
158                this.richTextBox1.Text+="总个数:\t"+myList.Count.ToString()+"\n";
159                foreach (DictionaryEntry myDE in  myList) 
160                {
161                      
162                    this.richTextBox1.Text +=("\t" +myDE.Key.ToString()+"\t" + myDE.Value.ToString()+"\n" );
163            
164                }

165
166            }

167        
168        
169
170    }

171
172    
173    public abstract class mrfuChart : Control   //创建一个抽象类
174    {
175 
176        public bool DataIsSorted = false;
177        public bool DataIsGrouped = true;
178        public bool IsStretch = true;
179        protected const int MINIMUM_PIECE = 1;
180        protected const int SMALLEST_DISPLAY_IN_PERCENT = 2;
181       // protected StringInt64PairedArray data;
182        public StringInt64PairedArray data;
183        public IDictionary Data
184        {
185            set
186            {
187                data = new StringInt64PairedArray (value);
188                
189                int i=data.Length ;
190                DataIsSorted=true;
191                DataIsGrouped=true;
192                if (DataIsSorted) data.SortValuesDesc ();
193                if (DataIsGrouped) data.GroupValues (MINIMUM_PIECE, 
194                                       SMALLEST_DISPLAY_IN_PERCENT);
195            
196            }

197        }

198        
199        public mrfuChart ()
200        {
201            Width = 100;
202            Height = 100;
203        }

204        
205    }

206
207    public class DrawPieChart : mrfuChart  //绘制饼状图  继承自抽象类
208    {
209        //定义自已的相关操作
210//        public int Diameter { get {return _diameter;} set {_diameter = value;}}
211//        private int _diameter = 100;
212//
213//        // Method to draw the pie chart 
214//        protected override void DrawChart()
215//        {
216//            // Calculate the size
217//            int d  = (int) Math.Min (LEFT_SECTION_RATIO * Width, 0.9 * Height);
218//            _diameter = (int) Math.Min (d, CHART_WIDTH_MAX);
219//            ChartWidth = _diameter;
220//
221//            int topX = (int) (SPACE_RATIO * Width / 2);
222//            int topY = (int) ((Height - _diameter) / 2);
223//            int startAngle = -90;
224//            int sweepAngle = 0;
225//
226//            // Loop to draw the Pies
227//            for (int i=0; i<data.Length; i++)
228//            {
229//                Brush theBrush = brush[i % brush.Length];
230//
231//                if (i < data.Keys.Length-1)
232//                    sweepAngle = (int) Math.Round( (float) data.Values[i] * 360 / data.TotalValue);
233//                else
234//                {
235//                    sweepAngle = 270 - startAngle;
236//                    if (data.IsGrouped)
237//                        theBrush = Brushes.Gold;
238//                }
239//                graphics.FillPie (theBrush, topX, topY, 
240//                    _diameter, _diameter, startAngle, sweepAngle);
241//                startAngle += (int) sweepAngle;
242//                startAngle = (startAngle>=360) ? startAngle - 360 : startAngle;
243//            }
244//        }
245
246
247    }

248
249
250    public class StringInt64PairedArray   //对哈希表转换成包含自己所要获取的相关数据集合的类
251    {
252        public string[] Keys get {return _keys;} }
253        public long[] Values get {return _values;} }
254        public long TotalValue get {return _totalValue;} }
255        public int Length {get {return Keys.Length;} }
256        public bool IsGrouped {get {return _isGrouped;} }
257
258        private long _totalValue = 0;
259        private string[] _keys;
260        private long[] _values;
261        private bool _isSortedDesc;
262        private bool _isGrouped;
263 
264        public StringInt64PairedArray (IDictionary pData)
265        {
266            _keys = new string [pData.Count];
267            _values = new long[pData.Count];
268            pData.Keys.CopyTo (_keys, 0);
269            pData.Values.CopyTo (_values, 0);
270            for (int i=0; i<_values.Length; i++
271                _totalValue += _values[i];
272            _isSortedDesc = false;
273            _isGrouped = false;
274        }

275
276        public void SortValuesDesc()
277        {
278            Array.Sort (_values, _keys, new DescendingComparer());  //DescendingComparer
279            _isSortedDesc = true;
280        }

281
282        public void GroupValues(int pCountMinimum, int pPercentMinimum)
283        {
284            if (!_isSortedDesc)
285                SortValuesDesc();
286
287            bool boolStop = false;
288            long sum = 0;
289            int i = 0;
290            while (i < _keys.Length && !boolStop)
291            {
292                if (i<pCountMinimum)
293                {
294                    sum += _values[i];
295                }

296                else
297                {
298                    sum += _values[i];
299                    float percent = _values[i] * 100 / (float) _totalValue;
300                    if (percent < pPercentMinimum)
301                    {
302                        long[] arTemp1 = new long[i+1];
303                        string[] arTemp2 = new string[i+1];
304
305                        Array.Copy (_values, arTemp1, i+1);
306                        Array.Copy (_keys, arTemp2, i+1);
307                        _values = arTemp1;
308                        _keys = arTemp2;
309                        _values[i] = _totalValue - sum;
310                        _keys[i] = "Others";
311                        boolStop = true;
312                        _isGrouped = true;
313                    }

314                }

315                i++;
316            }

317        }

318    }

319
320    class DescendingComparer : IComparer
321    {
322        public int Compare (Object x, Object y)
323        {
324            return Decimal.Compare ((long) y, (long) x);
325        }

326    }

327}

328
原文地址:https://www.cnblogs.com/furenjun/p/310654.html