1、数据库查询,数据转Dictionary,键值对中的值是List集合
public Dictionary<int, List<Message>> GetChildrenMessageOrder(List<int> ids)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("SELECT * FROM TABLE");
Dictionary<int, List<Message>> dict = new Dictionary<int, List<Message>>();
using (IDataReader reader = ExecuteDataReader(strSql.ToString()))
{
while (reader.Read())
{
int MessageOrderID = (int)reader["MessageOrderID"];
Message model = MessageFromReader(reader);
model.MessageOrderID = MessageOrderID;
if (dict.ContainsKey(MessageOrderID))
dict[MessageOrderID].Add(model);
else
dict.Add(MessageOrderID, new List<Message> { model });
}
}
return dict;
}
2、基本操作
public void Test()
{
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("userName", "jiou");
test.Add("u2", "xx");
foreach (var dic in test)
{
Console.Write("key: {0}\nvalue: {1}\n", dic.Key, dic.Value);
}
}
3、键值对中的值是List集合
public void Test()
{
Dictionary<int, List<Message>> dict = new Dictionary<int, List<Message>>();
foreach (var p in dict)
{
foreach (Invoice inv in miList)
{
foreach (Message m in p.Value)
{
if (m.MessageID == inv.MessageID)
{
if (m.Invoices == null)
m.Invoices = new List<Invoice>();
m.Invoices.Add(inv);
}
}
}
}
}
4、获取Dictionary集合中的值
/// <summary>
///
/// </summary>
public void GetDictionaryKey()
{
#region Dictionary添加数据
Dictionary<string, object> dictionary = new Dictionary<string, object>();
Dictionary<string, object> retData = new Dictionary<string, object>();
for (int i = 0; i <= 5; i++)
{
retData.Add("key" + i.ToString(), "value" + i.ToString());
}
dictionary["statusCode"] = "0000";
dictionary["statusMsg"] = "成功";
dictionary["data"] = new Dictionary<string, object> { { "CallBack", retData } };
#endregion
#region 获取Dictionary数据
string statusCode = Convert.ToString(dictionary["statusCode"]);
Dictionary<string, object> resultData = dictionary["data"] as Dictionary<string, object>;
Dictionary<string, object> resultCallBack = resultData["CallBack"] as Dictionary<string, object>;
#endregion
}
5、判断 Dictionary 中某个 key 值是否存在
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary["statusMsg"] = "成功";
string deviceId = string.Empty;
if (dictionary.TryGetValue("device_id", out deviceId))
{
// 推荐
}
if (dictionary.ContainsKey("statusCode"))
{
}
6、转换 Dictionary<string, dynamic> dynamic,dynamic,dynamic 数据
var tmpData = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(Convert.ToString(data));
7、Dictionary转成String字符串
“参数=参数值”的模式用“&”字符拼接成字符串
/// <summary>
/// Dictionary转成String字符串
/// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
/// </summary>
/// <param name="dicArray">需要拼接的数组</param>
/// <returns>拼接完成以后的字符串</returns>
public static string DictionaryToString(Dictionary<string, string> dicArray)
{
StringBuilder prestr = new StringBuilder();
if (dicArray.Count > 0)
{
foreach (KeyValuePair<string, string> temp in dicArray)
{
prestr.Append(temp.Key + "=" + temp.Value + "&");
}
//去掉最後一個&字符
int nLen = prestr.Length;
prestr.Remove(nLen - 1, 1);
}
return prestr.ToString();
}
/// <summary>
/// Dictionary转成String字符串
/// </summary>
/// <param name="dicList"></param>
/// <returns></returns>
public static String buildQueryStr(Dictionary<String, String> dicList)
{
String postStr = "";
foreach (var item in dicList)
{
postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
}
postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
return postStr;
}
8、Dictionary 转成 String[]数组
/// <summary>
/// Dictionary转成String[]数组
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string[] DictionaryToStrArray(Dictionary<string, string> dicArray)
{
string[] strArray = null;
if (dicArray.Count > 0)
{
List<string> list = new List<string>();
foreach (var item in dicArray)
{
list.Add(item.Value);
}
strArray = list.ToArray();
}
return strArray;
}
9、Dictionary 转成 Json
[HttpPost]
public async Task<IActionResult> Create()
{
await Task.Run(() => { });
Dictionary<string, object> data = new Dictionary<string, object>()
{
{"name", "admin"},
{"age", 18},
{"sex", "男"},
{"money", 1000000.66},
};
string json = JsonConvert.SerializeObject(data);
//string json = DictToJson(dicArray);
string json = DictionaryToJson(data);
return Ok(new
{
data = json
});
}
/// <summary>
/// Dictionary转成Json
/// </summary>
/// <param name="dicArray"></param>
/// <returns></returns>
private string DictToJson(Dictionary<string, string> dicArray)
{
StringBuilder prestr = new StringBuilder();
prestr.Append("[");
if (dicArray.Count > 0)
{
int i = 0;
foreach (KeyValuePair<string, string> temp in dicArray)
{
if (i == 0)
{
prestr.Append("{\"" + temp.Key + "\":" + temp.Value + ",");
}
else if (i == dicArray.Count - 1)
{
prestr.Append("\"" + temp.Key + "\":" + temp.Value + "}");
}
else
{
prestr.Append("\"" + temp.Key + "\":" + temp.Value + ",");
}
i++;
}
}
prestr.Append("]");
return prestr.ToString();
}
/// <summary>
/// Dictionary转成Json【推荐】
/// </summary>
/// <param name="dicArray"></param>
/// <returns></returns>
private string DictionaryToJson(Dictionary<string, object> date)
{
StringBuilder temp = new StringBuilder();
if (date.Count > 0)
{
int i = 0;
foreach (KeyValuePair<string, object> item in date)
{
object obj = item.Value;
if (obj is int)
Console.WriteLine("obj 是 int 类型");
else if (obj is string)
Console.WriteLine("obj 是 string 类型");
if (obj is string)
temp.Append("\"" + item.Key + "\":" + "\"" + item.Value + "\",");
else
temp.Append("\"" + item.Key + "\":" + item.Value + ",");
i++;
}
temp.Remove(temp.Length - 1, 1);
}
return "{" + temp.ToString() + "}";
}
10、Dictionary 转 对象;对象 转 Dictionary
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
Person person = new Person { Name = "John Doe", Age = 20 };
IDictionary<string, object> personDictionary = DictionaryExtensions.ToDictionary(person);
foreach (var item in personDictionary)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
Dictionary<string, object> dictionary = new Dictionary<string, object>
{
{ "Name", "aaaaaa" },
{ "Age", 30 }
};
Person obj = dictionary.ToObject<Person>();
}
}
/// <summary>
/// Dictionary 扩展
/// </summary>
public static class DictionaryExtensions
{
/// <summary>
/// Dictionary 转 对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T ToObject<T>(this IDictionary<string, object> source) where T : class, new()
{
T result = new T();
Type type = typeof(T);
foreach (KeyValuePair<string, object> item in source)
{
PropertyInfo property = type.GetProperty(item.Key);
if (property != null && property.CanWrite)
{
property.SetValue(result, item.Value, null);
}
}
return result;
}
/// <summary>
/// 对象 转 Dictionary
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static IDictionary<string, object> ToDictionary(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
var dictionary = new Dictionary<string, object>();
foreach (var property in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.CanRead)
{
dictionary[property.Name] = property.GetValue(obj, null);
}
}
return dictionary;
}
}
*
*
*
*
*
*
*
*
*