我希望你是我独家记忆

一段永远封存的记忆,随风而去
posts - 263, comments - 31, trackbacks - 0, articles - 3
   :: 首页 :: 新随笔 ::  :: 聚合  :: 管理

Dictionary<>实例

Posted on 2009-07-07 15:53 Hero 阅读(222) 评论(0)  编辑 收藏 引用 所属分类: C#积累
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 using System.IO;
 6 
 7 namespace Stream2
 8 {
 9     class Program
10     {
11         private static List<Dictionary<stringstring>>
12             GetData( out List<string>columns )
13         {
14             string strline;
15             string[] strArry;
16             char[] charArry = new char[] { ',' } ;//分割字符
17             List<Dictionary<stringstring>> data = new List<Dictionary<stringstring>>();
18 
19             columns = new List<string>();
20 
21             try
22             {
23                 //创建文件流
24                 FileStream filestream = new FileStream( "Log.txt", FileMode.OpenOrCreate ) ;
25                 StreamReader reader = new StreamReader( filestream );
26 
27                 //obtain the columns from the first line 
28                 //split row of data into string array
29 
30                 strline = reader.ReadLine();//读入第一行
31                 strArry = strline.Split( charArry );//获得“,”分割的列名称
32 
33                 forint i=0; i<=strArry.GetUpperBound(0); i++ )
34                 {
35                     columns.Add( strArry[i] );
36                 }
37 
38                 strline = reader.ReadLine();
39                 while( strline != null )
40                 {
41                     strArry = strline.Split( charArry );
42 
43                     Dictionary<stringstring> dataRow = new Dictionary<stringstring>();
44 
45                     forint i=0; i<=strArry.GetUpperBound(0); i++ )
46                     {
47                         dataRow.Add( columns[i], strArry[i] );
48                     }
49 
50                     data.Add( dataRow );
51 
52                     strline = reader.ReadLine();
53                 }
54 
55                 reader.Close();
56 
57                 return data;
58             }
59             catch ( IOException ex )
60             {
61                 Console.WriteLine( ex.ToString() );
62                 return data;
63             }
64 
65             return data;
66         }
67 
68 
69         static void Main( string[] args )
70         {
71             List<string> columns;
72             List<Dictionary<stringstring>> myData = GetData( out columns );
73 
74             foreach ( string column in columns )
75             {
76                 Console.Write( "{0,-20}", column ); 
77             }
78             Console.WriteLine();
79 
80             foreach ( Dictionary<stringstring> row in myData )
81             {
82                 foreach ( string column in columns )
83                 {
84                     Console.Write( "{0,-20}", row[column] );
85                 }
86                 Console.WriteLine();
87             }
88         }
89     }
90 }
91