日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 键值对 KeyValue 解析

發布時間:2023/12/31 C# 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# 键值对 KeyValue 解析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近看到一個輸入字符串或者字節數組解析成鍵值對的代碼,可能對大家有用,簡單的寫了一下。
當然,你可以用JSON.NET去處理JSON類型的鍵值對,網上很多資料,就不多說,這里主要說是類似于自定數據格式,類似這樣的字符串:

string data = "sdada=57.4,aaasd=1234,fdafdsa=3.2,fdsafdsa=3.515,fdsafd=-3.471,gfdasgfd=0.098,gfdsgf=148.926,測試1=99.999750,測試2=57.1";

當然可以用LINQ來解決。這里用比較傳統的方法,直接上代碼吧

/// <summary>/// 鍵值對解析Helper,修改matchKey作為鍵值之間的符號,matchValue為鍵值對之間的符號/// </summary>public static class KeyValueHelper{static Dictionary<object, object> conents = new Dictionary<object, object>();public static string matchKey {get;set;}public static string matchValue { get; set; }/// <summary>/// 解析輸入Bytes中的鍵值對/// </summary>/// <param name="data">輸入字節數組</param>/// <returns>解析后的鍵值對字典</returns>public static Dictionary<object, object> GetConentByBytes(byte[] data){conents.Clear();conents=GetConentByString(Encoding.Default.GetString(data));return conents;}/// <summary>/// 解析輸入字符串中的鍵值對/// </summary>/// <param name="data">輸入字符串</param>/// <returns>解析后的鍵值對字典</returns>public static Dictionary<object, object> GetConentByString(string data){conents.Clear();//Predicate<string> matchEqual = delegate(string value)//{// return value == "=" ? true : false;//};//Predicate<string> matchComma = delegate(string value)//{// return value == "," ? true : false;//};if (data.Substring(data.Length - 1) != matchValue){data = data + matchValue;}try{int pos = 0;int startIndex = 0;while (true){//Get Keypos = data.IndexOf(matchKey, startIndex);string key = data.Substring(startIndex, pos - startIndex);startIndex = pos + 1;//Get Valuepos = data.IndexOf(matchValue, startIndex);string value = data.Substring(startIndex, pos - startIndex);startIndex = pos + 1;conents.Add(key, value);if (startIndex >= data.Length){break;}}}catch(Exception ex){throw new Exception("Error Info: " + ex.ToString());}return conents;}}

測試下:

class Program{static void Main(string[] args){string data = "sdada=57.4,aaasd=1234,fdafdsa=3.2,fdsafdsa=3.515,fdsafd=-3.471,gfdasgfd=0.098,gfdsgf=148.926,測試1=99.999750,測試2=57.1";// 本文的測試字符串Key和Value是用“=”連接的,鍵值之間是“,”隔開的KeyValueHelper.matchKey = "=";KeyValueHelper.matchValue = ",";Dictionary<object, object> conents = KeyValueHelper.GetConentByString(data);Console.WriteLine(data);Console.WriteLine("result:");foreach (KeyValuePair<object ,object> e in conents){Console.WriteLine(string.Format("Key : {0} Value : {1}",e.Key.ToString(),e.Value.ToString()));}Console.ReadKey();}

運行結果:

收工。

總結

以上是生活随笔為你收集整理的C# 键值对 KeyValue 解析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。