你的位置:首页 > ASP.net教程

[ASP.net教程].NET 数据类型转换 方法


using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Web.Script.Serialization;

 

/// <summary>
/// 将字符串转为字典类型
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Dictionary<string, int> Str2Dic(string value)
{
Dictionary<string, int> IDs = new Dictionary<string, int>();
string[] str1 = value.Split(';');
for (int i = 0; i < str1.Length; i++)
{
string[] str2 = str1[i].Split(',');
if (!IDs.ContainsKey(str2[0]) && str2[0]!="")
{
IDs.Add(str2[0], int.Parse(str2[1]));
}
}
return IDs;
}

public Dictionary<string, string> StrToDic(string value)
{
Dictionary<string, string> list = new Dictionary<string, string>();
string[] str1 = value.Split('#');
for (int i = 0; i < str1.Length; i++)
{
string[] str2 = str1[i].Split(';');
if (!list.ContainsKey(str2[0]) && str2[0] != "")
{
list.Add(str2[0], str2[1]);
}
}
return list;
}

//字典转字符串 
public string DicToStr(Dictionary<string, string> list)
{
string result="";
foreach (KeyValuePair<string, string> l in list)
{
result += l.Key + ";" + l.Value + "#";
}
return result;
}

//List转字符串

public string ListToStr(List<string> list)
{
string result = "";
foreach (string s in list)
{
result += s + ",";
}
return result;
}

 


public List<string> StrToList(string str)
{
List<string> list = new List<string>();
string[] s = str.Split(',');
for (int i = 0; i < s.Length; i++)
{
if (s[i] != "" && !list.Contains(s[i]))
{
list.Add(s[i]);
}
}
return list;
}