gpt4 book ai didi

.net - 我可以顺序读取 YamlDotNet 映射吗?

转载 作者:行者123 更新时间:2023-12-03 17:50:35 25 4
gpt4 key购买 nike

是否可以按照源文档中出现的顺序访问映射的键? IE。如果我有这个简单的文档:

values:
first: something1
second: something2
third: something3

然后我就能够按原始顺序获取键序列:[第一,第二,第三]?

最佳答案

实现此目的的一种方法是使用 RepresentationModel API。它允许获取与底层结构紧密匹配的 YAML 文档表示:

var stream = new YamlStream();
stream.Load(new StringReader(yaml));

var document = stream.Documents.First();

var rootMapping = (YamlMappingNode)document.RootNode;
var valuesMapping = (YamlMappingNode)rootMapping.Children[new YamlScalarNode("values")];

foreach(var tuple in valuesMapping.Children)
{
Console.WriteLine("{0} => {1}", tuple.Key, tuple.Value);
}

这种方法的缺点是您需要“手动”解析文档。另一种方法是使用序列化,并使用保留顺序的类型。我不知道 IDictionary<TKey, TValue> 有任何现成的实现具有此特性,但如果您不关心高性能,则实现起来相当简单:

// NB: This is a minimal implementation that is intended for demonstration purposes.
// Most of the methods are not implemented, and the ones that are are not efficient.
public class OrderPreservingDictionary<TKey, TValue>
: List<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>
{
public void Add(TKey key, TValue value)
{
Add(new KeyValuePair<TKey, TValue>(key, value));
}

public bool ContainsKey(TKey key)
{
throw new NotImplementedException();
}

public ICollection<TKey> Keys
{
get { throw new NotImplementedException(); }
}

public bool Remove(TKey key)
{
throw new NotImplementedException();
}

public bool TryGetValue(TKey key, out TValue value)
{
throw new NotImplementedException();
}

public ICollection<TValue> Values
{
get { throw new NotImplementedException(); }
}

public TValue this[TKey key]
{
get
{
return this.First(e => e.Key.Equals(key)).Value;
}
set
{
Add(key, value);
}
}
}

一旦你有了这样的容器,你就可以利用Serialization解析文档的API:

var deserializer = new Deserializer();
var result = deserializer.Deserialize<Dictionary<string, OrderPreservingDictionary<string, string>>>(new StringReader(yaml));

foreach(var tuple in result["values"])
{
Console.WriteLine("{0} => {1}", tuple.Key, tuple.Value);
}

You can see a fully working example in this fiddle

关于.net - 我可以顺序读取 YamlDotNet 映射吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29984486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com