从关联数组C#中检索值

我陷入下一个问题。

我从包含以下内容的文本文件中读取了一行:

(("ITEM" "05") ("NUMBER" "1") ("DESCRIPTION" "*RECHTE INSTEEKKOP. 1/4\"-8MM") ("ARTICLENUMBER" "S110010000104"))

In Lisp this is a List and for retrieving the value of eg ITEM in Lisp:

(cadr (assoc "ITEM" str))

This gives 05

我怎样才能简单地在C#中实现呢?

评论
  • 抄凝雪
    抄凝雪 回复

    您可以使用Regex解析值,然后获取结果。例如,

    var valueCollection = Regex.Matches(datastring,@"\(""(?<Key>.+?(?=""))""\s+""(?<Value>.+?(?=""))""\)")
                                     .Cast<Match>()
                                    .Select(x=>new {Key = x.Groups["Key"].Value,Value = x.Groups["Value"].Value,});
    
    

    这将为您提供以下收藏

    enter image description here

    现在,您可以使用Linq获取Key等于“ ITEM”的值。

    var itemValue = valueCollection.First(x=>x.Key=="ITEM").Value;
    

    或者,您可以将字符串转换为Dictionary为

    var valueCollection = Regex.Matches(datastring,@"\(""(?<Key>.+?(?=""))""\s+""(?<Value>.+?(?=""))""\)")
                                     .Cast<Match>()
                                     .ToDictionary(x=>x.Groups["Key"].Value,y=>y.Groups["Value"].Value);
    
    

    You could now parse the required ITEM value as

    var itemValue = valueCollection["ITEM"];
    
  • 壁咚
    壁咚 回复

    Another approach is using Split function

    string values = "((\"ITEM\" \"05\") (\"NUMBER\" \"1\") (\"DESCRIPTION\" \" * RECHTE INSTEEKKOP. 1 / 4\" - 8MM\") (\"ARTICLENUMBER\" \"S110010000104\"))";
    
    var keyValuePairs = values.Split(new[] { "(", ")", " (", ") " }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(s => s.Split(new[] { ' ' }, 2))
                        .ToDictionary(x => x[0].ToString(), x => x[1].ToString());