数组和字符串互转方法:
string str = "1,2,3,4,5,6,7";
string[] strArray = str.Split(','); //字符串转数组
str = string.Empty;
str = string.Join(",", strArray);//数组转成字符串
字符串数组转整数数组
//\\//\\//\\//\\数组类型转换//\\//\\//\\
public static int ToInt(this string target)
{
int i;
return int.TryParse(target, out i) ? i : 0;
}
private void s_数组类型转换()
{
string a = "15,5,8,9,2,8,4,7";
string[] aa = a.Split(',');
// 方法1 使用 Array.ConvertAll
int[] aaa = Array.ConvertAll(aa, new Converter<string, int>(StrToInt));
//方法2 使用数组循环分别转换
int[] b = new int[aa.Length];
for (int i = 0; i < aa.Length; i++)
{
int.TryParse(aa[i], out b[i]);
}
//方法3
for (int o=0; o < aa.Length; o++)
{
b[o] = int.Parse(aa[o]);
}
}
俩数组差集、交集、并集方法:
int[] x = {6, 7, 8, 9, 10};
int[] y = {4, 5, 6, 7, 8};
int[] diffXToY = x.Except(y).ToArray(); // 在数组x中且不在数组y中的元素数组 {9, 10}
int[] intersection = x.Intersect(y).ToArray(); // 即在数组x中也在数组y中的元素数组 {6, 7, 8}
int[] union = x.Union(y).ToArray(); // 合并数组x和数组y并剔除重复元素后的元素数组 {6, 7, 8, 9, 10, 4, 5}
//注:合并数组其他方法参考
public static T[] Merge<T>(T[] arr, T[] other)
{
// 常规方法
T[] buffer = new T[arr.Length + other.Length];
arr.CopyTo(buffer, 0);
other.CopyTo(buffer, arr.Length);
return buffer;
// Linq 方法
return arr.Concat(other).ToArray();
}
字符串转日期的方法
- 方法一:Convert.ToDateTime(string)
Convert.ToDateTime(string); //string格式有要求,必须是yyyy-MM-dd hh:mm:ss
- 方法二:Convert.ToDateTime(string, IFormatProvider)
DateTime dt;
DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
dtFormat.ShortDatePattern = "yyyy/MM/dd";
dt = Convert.ToDateTime("2011/05/26", dtFormat);
- 方法三:DateTime.ParseExact()
string dateString = "20110526";
DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
//或者
DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);