有誰知道一個C#中的等價偶爾PHP任務的:轉換點符號串多維數組
Convert dot syntax like "this.that.other" to multi-dimensional array in PHP
也就是說,像level1.level2.level3 = item
字符串列表轉換成字典或多維數組?
我假設字典需要保存object
類型的項目,如果它是最後一個項目,我以後會將它們投射到Dictionary<string, string>
或string
。
有誰知道一個C#中的等價偶爾PHP任務的:轉換點符號串多維數組
Convert dot syntax like "this.that.other" to multi-dimensional array in PHP
也就是說,像level1.level2.level3 = item
字符串列表轉換成字典或多維數組?
我假設字典需要保存object
類型的項目,如果它是最後一個項目,我以後會將它們投射到Dictionary<string, string>
或string
。
這樣的代碼有用嗎?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "level1.level2.level3 = item";
string pattern = "^(?'keys'[^=]+)=(?'value'.*)";
Match match = Regex.Match(input, pattern);
string value = match.Groups["value"].Value.Trim();
string[] keys = match.Groups["keys"].Value.Trim().Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
foreach (string key in keys)
{
if (dict.ContainsKey("key"))
{
dict[key].Add(value);
}
else
{
dict.Add(key, new List<string>() { value });
}
}
}
}
}
我想你可以做這樣的,雖然(我敢肯定,更多的優化可以做)
using System;
using System.Collections.Generic;
public class Program
{
public class IndexedTree {
private readonly IDictionary<string, IndexedTree> _me;
private object _value;
private readonly string _splitKey = ".";
public IndexedTree this[string key] {
get {
return _me[key];
}
}
public object Value { get; set; }
public void Add(string dottedItem) {
if (string.IsNullOrWhiteSpace(dottedItem)) {
throw new ArgumentException("dottedItem cannot be empty");
}
int index;
if ((index = dottedItem.IndexOf(_splitKey)) < 0) {
throw new ArgumentException("dottedItem didn't contain " + _splitKey);
}
string key = dottedItem.Substring(0, index), rest = dottedItem.Substring(index + 1);
IndexedTree child;
if (_me.ContainsKey(key)) {
child = _me[key];
} else {
child = new IndexedTree(_splitKey);
_me.Add(key, child);
}
if (rest.IndexOf(_splitKey) >= 0) {
child.Add(rest);
} else {
// maybe it can be checked if there is already a value set here or not
// in case there is a warning or error might be more appropriate
child.Value = rest;
}
}
public IndexedTree(string splitKey) {
_splitKey = splitKey;
_me = new Dictionary<string, IndexedTree>();
}
}
public static void Main()
{
IndexedTree tree = new IndexedTree(".");
tree.Add("Level1.Level2.Level3.Item");
tree.Add("Level1.Level2.Value");
Console.WriteLine(tree["Level1"]["Level2"].Value);
Console.WriteLine(tree["Level1"]["Level2"]["Level3"].Value);
}
}
你可以在這裏看到的結果: https://dotnetfiddle.net/EGagoz
我認爲這將需要一定程度的反思來實現這一點。可能有助於說明這個用例,因爲可能有其他解決方案來解決您的問題 –
您是否需要將1個字符串解析爲字典,還是存在更復雜的用例?只需拆分文本可以很簡單,就像這樣https://dotnetfiddle.net/NEbUK7 – Icepickle
@Ippickle否,列表中的所有字符串。如果循環遇到現有的鍵,那麼它應該將該字符串附加到現有的子詞典(希望這有意義?)。 – silkfire