当前位置: 移动技术网 > IT编程>开发语言>c# > C# 汉字获取拼音首字母,给数据库中的姓名添加首字母

C# 汉字获取拼音首字母,给数据库中的姓名添加首字母

2019年10月15日  | 移动技术网IT编程  | 我要评论

本方案采用微软官方语言包

(下载链接: https://pan.baidu.com/s/10i1bhtdfr4-q_xkvhuezma 提取码: p3nk   

chncharinfo.dll 用于获取首字母

文件夹中的压缩包为官方包,包括日文、繁体等 。 用法一样

用哪个就安装到 c:\program files (x86)\microsoft visual studio international pack 文件夹下 

安装完会出现对应的文件夹,拿到.dll结尾的 放入项目的bin文件夹中

官方地址移步---->

根据汉子获取拼音

先将 chncharinfo.dll 放入项目的bin文件夹中

在程序中引入@using microsoft.international.converters.pinyinconverter

 

@using system;
@using microsoft.international.converters.pinyinconverter

1    public class surname 2 { 3 public string name { get; set; } 4 public string pinying { get; set; } 5 } 6 /// <summary> 7 /// 汉字转化为拼音首字母 8 /// </summary> 9 /// <param name="str">汉字 赵钱孙里王</param> 10 /// <returns>首字母 </returns> 11 public static list<surname> getfirstpinyin(string str) 12 { 13 list<surname> surnamelist = new list<surname>(); 14 foreach (char obj in str) 15 { 16 surname surname = new surname(); 17 try 18 { 19 chinesechar chinesechar = new chinesechar(obj); 20 string t = chinesechar.pinyins[0].tostring(); 21 surname.name = obj.tostring(); 22 surname.pinying= t.substring(0, 1); 23 } 24 catch 25 { 26 surname.name = obj.tostring(); 27 } 28 surnamelist.add(surname); 29 } 30 return surnamelist; 31 }

直接调用  var pylist=getfirstpinyin("赵钱孙李王");

 

程序使用实例

 

数据库:mysql

需求:按数据表中的 姓名 添加首字母列

id 主键

name 姓名

firstname首字母

 1 var subnamelist = repository.current.executequery(string.format("select distinct left(name, 1)name from {0}_table1 where  firstname is  null", repository.current.name),commandtype.text).tolist();//数据表中没有首字母的姓
 2         if (subnamelist.count != 0)
 3         {//首字母为空的数据  查出的数据为去重后姓名的姓
 4             var subname = "";
 5             foreach (var item in subnamelist)
 6             {
 7                 subname += item["name"];//例:赵钱孙李
 8             }
 9             var first = getfirstpinyin(subname);//调用转拼音的方法
10 var sqlset = "(case left(name, 1) ";//拼接修改的sql语句 会将表中首字母列为空的数据修改 11 var sqlwhere = " find_in_set(left(name,1),'"; 12 foreach (var surnamelist in first) 13 { 14 sqlset += " when '" + surnamelist.name + "' then '" + surnamelist.pinying + "'"; 15 sqlwhere += surnamelist.name + ","; 16 } 17 sqlset += " end )"; 18 sqlwhere += " ') "; 19 var upsql = string.format("update {0}_table1 set firstname={1} where firstname is null and {2} ", repository.current.name, sqlset, sqlwhere); 20 repository.current.executenonquery(upsql, commandtype.text);//执行sql 21 };

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网