准备:
微软官方出了一个专用的汉字转拼音包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 FilesMicrosoft Visual Studio International PackSimplified Chinese Pin-Yin Conversion Library 和C:Program FilesMicrosoft Visual Studio International PackTraditional 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