2016年8月5日星期五
C# 應用雜湊表(Hashtable)
●一.雜湊表(Hashtable)簡述
在.NET Framework中,Hashtable是System.Collections命名空間提供的一個容器,用於處理和表現類似key/value的鍵值對,其中key通常可用來快速查找,同時key是區分大小寫;value用於存儲對應于key的值。Hashtable中key/value鍵值對均為object類型,所以Hashtable可以支援任何類型的key/value鍵值對.
●二.雜湊表的簡單操作
在雜湊表中添加一個key/value鍵值對:HashtableObject.Add(key,value);
在雜湊表中去除某個key/value鍵值對:HashtableObject.Remove(key);
從雜湊表中移除所有元素: HashtableObject.Clear();
判斷雜湊表是否包含特定鍵key: HashtableObject.Contains(key);
下面主控台程式將包含以上所有操作:
using System;
using System.Collections; //使用Hashtable時,必須引入這個命名空間
class hashtable
{
public static void Main()
{
Hashtable ht=new Hashtable(); //創建一個Hashtable實例
ht.Add("E","e");//添加key/value鍵值對
ht.Add("A","a");
ht.Add("C","c");
ht.Add("B","b");
string s=(string)ht["A"];
if(ht.Contains("E")) //判斷雜湊表是否包含特定鍵,其傳回值為true或false
Console.WriteLine("the E key:exist");
ht.Remove("C");//移除一個key/value鍵值對
Console.WriteLine(ht["A"]);//此處輸出a
ht.Clear();//移除所有元素
Console.WriteLine(ht["A"]); //此處將不會有任何輸出
}
}
●三,遍歷雜湊表
遍歷雜湊表需要用到DictionaryEntry Object,代碼如下:
for(DictionaryEntry de in ht) //ht為一個Hashtable實例
{
Console.WriteLine(de.Key);//de.Key對應于key/value鍵值對key
Console.WriteLine(de.Value);//de.Key對應于key/value鍵值對value
}
●四,對雜湊表進行排序
對雜湊表進行排序在這裡的定義是對key/value鍵值對中的key按一定規則重新排列,但是實際上這個定義是不能實現的,因為我們無法直接在Hashtable進行對key進行重新排列,如果需要Hashtable提供某種規則的輸出,可以採用一種變通的做法:
ArrayList akeys=new ArrayList(ht.Keys); //別忘了導入System.Collections
akeys.Sort(); //按字母順序進行排序
foreach(string skey in akeys)
{
Console.Write(skey + ":");
Console.WriteLine(ht[skey]);//排序後輸出
}
注意:用foreach
下面是一個簡單的例子:
class SampleHashtable
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
// Create and initialize a new Hashtable.
Hashtable table = new Hashtable();
//Student Name, Grade
table.Add("leiwanjun", 100);
table.Add("wanghuan", 87);
table.Add("wuhailong", 92);
table.Add("renyao", 76);
table.Add("tanghonglei", 84);
table.Add("chenxiaoping", 91);
table.Add("liupeixun", 80);
table.Add("huyoumou", 87);
// Display the properties and values of the Hashtable.
Console.WriteLine("Count: {0}", table.Count);
PrintTable(table);
Console.WriteLine();
int g = (int) table["wuhailong"];
Console.WriteLine ("wuhailong's grade is: {0}", g);
Console.WriteLine();
PrintItems ("All Names", table.Keys);
Console.WriteLine();
PrintItems ("All Grades", table.Values);
}
public static void PrintTable( Hashtable myList)
{
Console.WriteLine ("{0, -15} {1, -15}", "Name","Grade");
Console.WriteLine ("{0, -15} {1, -15}", "----","-----");
// // 排序
// ArrayList al = new ArrayList(myList.Keys);
// al.Sort();
// foreach (string Name in al)
// {
// Console.WriteLine("{0, -15} {1, -15}", Name, myList[Name]);
// }
// //
//遍歷雜湊表中的每個元素,直接輸出
foreach (DictionaryEntry e in myList)
{
Console.WriteLine ("{0, -15} {1, -15}", e.Key, e.Value);
}
}
public static void PrintItems(string title, IEnumerable myList )
{
Console.Write ("{0}: ", title);
StringBuilder sb = new StringBuilder();
foreach (object o in myList)
{
sb.AppendFormat( "{0}, ", o);
}
sb.Remove(sb.Length - 2, 2);
Console.WriteLine(sb);
2016年7月28日星期四
Npgsql
初始化
NpgsqlConnection()
// Connect to a PostgreSQL database NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres; " + "Password=pwd;Database=postgres;"); conn.Open();
NpgsqlCommand(string cmdText)
查詢返回單行
// Define a query returning a single row result set NpgsqlCommand command = new NpgsqlCommand("SELECT COUNT(*) FROM cities", conn); // Execute the query and obtain the value of the first column of the first row Int64 count = (Int64)command.ExecuteScalar(); Console.Write("{0}\n", count);
ExecuteScalar()
執行查詢,並在由該查詢返回的結果集返回第一行的第一列。額外的列或行被忽略。
查詢
// Define a query NpgsqlCommand command = new NpgsqlCommand("SELECT city, state FROM cities", conn); // Execute the query and obtain a result set NpgsqlDataReader dr = command.ExecuteReader(); // Output rows while (dr.Read()) Console.Write("{0}\t{1} \n", dr[0], dr[1]);
Consider a procedure that returns multiple result sets to the caller:
-- Procedure that returns multiple result sets (cursors) CREATE OR REPLACE FUNCTION show_cities_multiple() RETURNS SETOF refcursor AS $$ DECLARE ref1 refcursor; -- Declare cursor variables ref2 refcursor; BEGIN OPEN ref1 FOR SELECT city, state FROM cities WHERE state = 'CA'; -- Open the first cursor RETURN NEXT ref1; -- Return the cursor to the caller OPEN ref2 FOR SELECT city, state FROM cities WHERE state = 'TX'; -- Open the second cursor RETURN NEXT ref2; -- Return the cursor to the caller END; $$ LANGUAGE plpgsql;The stored procedure returns 2 result sets. You can process the first result the same way as if the procedure returned a single result set, and then use NextResult(); method of the DataReader to switch to the next result set and so on:
using System; using System.Data; using Npgsql; class Sample { static void Main(string[] args) { // Connect to PostgreSQL NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres; " + "Password=pwd;Database=postgres;"); conn.Open(); // Start a transaction as it is required to work with cursors in PostgreSQL NpgsqlTransaction tran = conn.BeginTransaction(); // Define a command to call stored procedure show_cities_multiple NpgsqlCommand command = new NpgsqlCommand("show_cities_multiple", conn); command.CommandType = CommandType.StoredProcedure; // Execute the stored procedure and obtain the first result set NpgsqlDataReader dr = command.ExecuteReader(); // Output the rows of the first result set while (dr.Read()) Console.Write("{0}\t{1} \n", dr[0], dr[1]); // Switch to the second result set dr.NextResult(); // Output the rows of the second result set while (dr.Read()) Console.Write("{0}\t{1} \n", dr[0], dr[1]); tran.Commit(); conn.Close(); } }
PostgreSQL的創建自動遞增的主鍵
方法1:
CREATE TABLE test_b
(
id serial PRIMARY KEY,
name character varying(128)
);
(
id serial PRIMARY KEY,
name character varying(128)
);
方法2:
CREATE TABLE test_c
(
id integer PRIMARY KEY,
name character varying(128)
);
(
id integer PRIMARY KEY,
name character varying(128)
);
CREATE SEQUENCE test_c_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
alter table test_c alter column id set default nextval('test_c_id_seq');
2016年1月28日星期四
C/C++ 宏中的單/雙井號( # and ## )
一、一般用法
# 的功能是將其後面的宏參數進行字符串化操作(Stringfication ),簡單說就是在對它所引用的宏變量通過替換後在其左右各加上一個雙引號。比如下面代碼中的宏:
#define WARN_IF(EXP) \
do{ if (EXP) \
fprintf(stderr, "Warning: " #EXP "\n"); } \
while(0)
那麼實際使用中會出現下面所示的替換過程:
WARN_IF (divider == 0);
2016年1月27日星期三
2016年1月24日星期日
Docker 命令
下載官方的ubuntu image:
sudo docker pull ubuntu
然後運行hello world:
sudo docker run ubuntu /bin/echo hello world
三種運行命令的模式
短暫方式,就是剛剛的那個”hello world”,命令執行完後,container就終止了,不過並沒有消失,可以用
sudo docker ps -a看一下所有的container,第一個就是剛剛執行過的container,可以再次執行一遍:2016年1月23日星期六
2016年1月21日星期四
apt-get 更新套件清單變更成其他國家的伺服器
1. 備份 sources.list
開始之前,請記得先用下面的指令來做個備份,以防萬一哩 !
sudo cp /etc/apt/sources.list /etc/apt/sources.list.BAK
2016年1月18日星期一
Python SimpleHTTPServer
Python 程式有一個 -m 選項,可以直接把模組拿來當做 Script 執行,所以,只要使用 -m 選項再加上 SimpleHTTPServer 就可以馬上啟動一個 HTTP Server,而這個 HTTP Server 預設會列出目前所在資料夾的檔案清單,因此,如果要分享檔案的話,就可以建一個資料夾,然後,把要分享的檔案放進去,之後,再進到那個資料夾來啟用 SimpleHTTPServer 模,這樣,就可以讓別人透過網頁來存取這個資料夾裡的檔案哩 ! 下面就是操作的步驟 ...
2016年1月11日星期一
使用SSH的X11 Forwarding遠程執行GUI程序
使用SSH的X11 Forwarding遠程執行GUI程序
SSH的X11 Forwarding功能提供了一個非常好的方法,在你的本地主機上執行遠程主機的GUI程序。比如你的開發環境可能是CentOS,你需要在CentOS下編碼。但你的工作環境可能是Ubuntu,你在Ubuntu下收發郵件,瀏覽網頁。你當然可以使用CentOS同時作為你的開發與工作環境,但你將不得不忍受CentOS陳舊的桌面系統及用戶體驗。你也可以通過SSH遠程登錄到你的CentOS系統,然後使用CLI程序(如Vim)完成你的工作,但如果能使用更方便的GUI程序時(如Eclipse),為什麼不呢?現在我們來看看如何實現在Ubuntu上遠程執行CentOS主機的GUI程序Eclipse。
2016年1月2日星期六
訂閱:
留言 (Atom)
