【String转Array】
string str = "123asd456asd789";
单字符: string[] a0 = str.Split('a');
多字符: string[] a1 = Regex.Split(str, @"asd"); //using System.Text.RegularExpressions;
【Array转String】
int[] i = { 12, 34, 123, 4, 12, 123, 54, 5, 122, 23 };
string str=string.Join("",i);
【JSON转List/Class】using Newtonsoft.Json;
使用 JsonConvert.DeserializeObject
string jsonStr = "[{\"id\":1,\"name\":\"liuph1\",\"age\":20},{\"id\":2,\"name\":\"liuph2\",\"age\":21}]";
List<className> ls = JsonConvert.DeserializeObject<List<className>>(jsonStr);
【List/Class转JSON】using Newtonsoft.Json;
使用 JsonConvert.SerializeObject
string jsonStr = JsonConvert.SerializeObject(ls);
【string转byte[]】
byte[] bt = Encoding.UTF8.GetBytes("Hello World!");//string=>byte[]
【byte[]转string】
string str = Encoding.Default.GetString(bt);//byte[]=>string
【URL转码】
string en= HttpUtility.UrlEncode("http://www.baidu.com");
【URL解码】
string de= HttpUtility.UrlDecode(en);
【自定义实体之间的转换】
用explicit来定义. 以下代码 可以实现 test和test1之间的转换。
test1 t1 = new test1();
test t = new test();
t=(test)t1;
t1=(test1)t;
1 public class test 2 { 3 public int Id; 4 public string Name; 5 public DateTime Time = DateTime.Now; 6 public static explicit operator test(test1 t) 7 { 8 return new test 9 { 10 Id = t.Id, 11 Name = t.Name + t.Time.ToString("yyyy-MM-dd HH:mm:ss"), 12 Time = t.Time 13 }; 14 } 15 } 16 public class test1 17 { 18 public int Id; 19 public string Name; 20 public DateTime Time = DateTime.Now; 21 public static explicit operator test1(test t) 22 { 23 return new test1 24 { 25 Id = t.Id, 26 Name = t.Name + t.Time.ToString("yyyy-MM-dd HH:mm:ss"), 27 Time = t.Time 28 }; 29 } 30 }
获取时间戳
1 System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 2 return (time - startTime).TotalSeconds.ToString("0");
集合ToDictionary时key必须唯一,可以用ToLookUp,相当于Dictionary<key,T>或Dictionary<key,List<T>>
1 var lss = ls.ToLookup(x => x.userId);//ls是一个List 2 foreach (var item in lss) 3 { 4 var key = item.Key; 5 foreach (var item1 in item) 6 { 7 var val = item1.userName + item1.password; 8 } 9 }