在C#中创建字符串或列表(包含HTML标记)
A有这样的字符串:
string s = @" 11 12 21 22 31 32 ";
如何创建Dictionary d = new Dictionary();
从字符串s得到相同的结果:
d.Add(11, 12); d.Add(21, 22); d.Add(31, 32);
您应该使用HTML Agility Pack 。
例如:(已测试)
var doc = new HtmlDocument(); doc.LoadHtml(s); var dict = doc.DocumentNode.Descendants("tr") .ToDictionary( tr => int.Parse(tr.Descendants("td").First().InnerText), tr => int.Parse(tr.Descendants("td").Last().InnerText) );
如果HTML总是格式正确,您可以使用LINQ-to-XML; 代码几乎完全相同。
码
using RE=System.Text.RegularExpressions; .... public void Run() { string s=@" 11 12 21 22 31 32 "; var mcol= RE.Regex.Matches(s,"(\\d+) (\\d+) "); var d = new Dictionary(); foreach(RE.Match match in mcol) d.Add(Int32.Parse(match.Groups[1].Value), Int32.Parse(match.Groups[2].Value)); foreach (var key in d.Keys) System.Console.WriteLine(" {0}={1}", key, d[key]); }
string s = @" 11 12 21 22 31 32 "; XPathDocument doc = new XPathDocument(XmlReader.Create(new StringReader(s), new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment, IgnoreWhitespace = true })); Dictionary dict = doc.CreateNavigator() .Select("tr") .Cast() .ToDictionary( r => r.SelectSingleNode("td[1]").ValueAsInt, r => r.SelectSingleNode("td[2]").ValueAsInt );
如果您不想使用HTML敏捷包,可以尝试类似于:
var arr = s.Replace("", "").Split(" (); foreach (var row in arr) { var itm = row.Replace("", "").Split(" ", StringSplitOptions.RemoveEmptyEntries); d.Add(int.Parse(itm[0]), int.Parse(itm[1]); }
(另)
var s = "11 12 21 22 31 32 "; var rows = s.Split( new[] { "" }, StringSplitOptions.None ); var results = new Dictionary(); foreach ( var row in rows ) { var cols = row.Split( new[] { "" }, StringSplitOptions.None ); var vals = new List(); foreach ( var col in cols ) { var val = col.Replace( "", string.Empty ).Replace( " ", string.Empty ); int intVal; if ( int.TryParse( val, out intVal ) ) vals.Add( intVal ); } if ( vals.Count == 2 ) results.Add( vals[0], vals[1] ); }
使用RE = System.Text.RegularExpressions;
….
public void Run(){string s = @“1112 2122 3132”;
var mcol= RE.Regex.Matches(s,"(\\d+) (\\d+) "); var d = new Dictionary(); foreach(RE.Match match in mcol) d.Add(Int32.Parse(match.Groups[1].Value), Int32.Parse(match.Groups[2].Value)); foreach (var key in d.Keys) System.Console.WriteLine(" {0}={1}", key, d[key]);
}