數組和字符串互轉方法:
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);