准備:
微軟官方出了一個專用的漢字轉拼音包Microsoft Visual Studio International Pack 1.0 SR1
首先到官網http://www.microsoft.com/zh-cn/download/details.aspx?id=15251下載安裝包,下載完后解壓vsintlpack1,里面有7個安裝包,只需安裝CHSPinYinConv(跟拼音相關)和CHTCHSConv(簡體和繁體間的轉換)這兩個包就可以了,安裝完畢后,需要在VS里添加引用。
將C:\Program Files\Microsoft Visual Studio International Pack\Simplified Chinese Pin-Yin Conversion Library 和C:\Program Files\Microsoft Visual Studio International Pack\Traditional Chinese to Simplified Chinese Conversion Library and Add-In Tool下的dll 拷貝到項目的dll文件夾下(我的是Reference),接下來添加引用
Code:
using Microsoft.International.Converters.PinYinConverter;
#region==模糊搜索==
private void MistinessSel()
{
string selwords = GetFormString("words");
if (selwords != "")
{
//判斷是漢字還是字母
string pattern = @"^[A-Za-z]+$";
Regex regex = new Regex(pattern);
List<Model.t_category> list = null;
List<Model.t_category> categorylist = new List<Model.t_category>();
//字母模糊搜索
if (regex.IsMatch(selwords))
{
selwords = selwords.ToLower();
list = new BLL.t_category().GetModelList(" ParentID!=0 ");
//拼音模糊查詢法
for (int i = 0; i < list.Count; i++)
{
//StringBuilder str = new StringBuilder();//定義一個可變長度的字符串
//char[] chs; //定義一個字符數組來接收每個漢字的拼音
string spells = "";
//遍歷F_ConnName字段中所有漢字
foreach (char c in list[i].Name.ToCharArray())
{
//驗證該漢字是否合法
if (ChineseChar.IsValidChar(c))
{
ChineseChar CC = new ChineseChar(c);
//將該漢字轉化為拼音集合
ReadOnlyCollection<string> roc = CC.Pinyins;
//獲取集合中第一個數據即為該漢字的拼音
spells += roc[0].ToLower();
}
}
if (spells.Contains(selwords))
{
categorylist.Add(list[i]);
}
}
}
else
{
categorylist = new BLL.t_category().GetModelList(" ParentID!=0 and Name LIKE '%" + selwords + "%'"); ;
}
ResponseText(Newtonsoft.Json.JsonConvert.SerializeObject(new { res = 1, list = categorylist }));
}
else {
ResponseText(Newtonsoft.Json.JsonConvert.SerializeObject(new { res = 0 }));
}
}
#endregion