本人决定把工作中经常用到的C#编程技巧记录在博客中,以备查阅。
所有的代码均在 .NET2.0 下测试通过。引用命名空间如下:
Code
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Text;
5using System.Text.RegularExpressions;
(1)、删除List<T>中元素相同的项。
Code
1public static void GetUniqueList()
2{
3 int[] a = {2,3,3,4,5,6,6,7,8,9,10,12,12,12,4,18,20,20};
4 List<int> lst = new List<int>(a);
5 List<int> retLst = new List<int>();
6 foreach (int item in lst)
7 {
8 if (retLst.IndexOf(item) == -1)
9 {
10 retLst.Add(item);
11 Console.WriteLine(item);
12 }
13 }
14}
(2)、验证手机号
Code
public static void VerifyMobilephone()
{
Regex rgxChinaUnicom = new Regex(@"^(130|131|132|133|153|155|156)[0-9]{8}$");
Regex rgxChinaMobile = new Regex(@"^(134|135|136|137|138|139|150|157|158|159)[0-9]{8}$");
Console.WriteLine("please input Mobilephone Number:");
string a = Console.ReadLine();
if(rgxChinaMobile.IsMatch(a))
{
Console.WriteLine("It is ChinaMobile Number!");
}
else if (rgxChinaUnicom.IsMatch(a))
{
Console.WriteLine("It is ChinaUnicom Number!");
}
else
{
Console.WriteLine("you input a Error Number!");
}
}
(3)、在Access中插入一条记录后得到最新的自动编号
Code
1public int GetIDInsert(string XSqlString)
2{
3 OleDbConnection con=DB.createcon();
4 OleDbCommand cmd = new OleDbCommand(XSqlString, con);
5 con.Open();
6 cmd.ExecuteNonQuery();
7 cmd.CommandText = "SELECT @@IDENTITY";
8 int Id = (int)cmd.ExecuteScalar();
9 con.Close();
10 return Id;
11}
(4)、验证字符串中是否包含中文和中文字符
Code
protected static bool HaveChinese(string str)
{
if (Regex.IsMatch(str, @"[\u4E00-\u9FA5|,。?:;‘’!“”……——、()【】《》¥]+"))
{
return true;
}
else
{
return false;
}
}