【问题标题】:Dictionaries and DotLiquid字典和 DotLiquid
【发布时间】:2012-02-29 17:10:43
【问题描述】:

我有一个基本的 .NET 字典(字典)。在我的 ToLiquid 方法中,我确实序列化/公开了 Dictionary 对象。我的问题是如何像在常规 .NET 中那样迭代流动模板中的键?似乎您必须知道实际的键才能访问液体模板中的值。

我知道您可以像这样访问液体模板中的值

item.dictionary["myKey"]

但是我不知道实际的键,所以我更喜欢使用 DotLiquid 中的“for”构造来迭代键以获得各种值。由于“for”构造适用于集合,而 Dictionary 是一个集合,我认为这可以通过某种方式完成,但我尝试过的所有排列都失败了。

任何帮助将不胜感激。

【问题讨论】:

  • Dictionary 有一个属性可以在键上返回一个迭代器:Keys

标签: .net liquid


【解决方案1】:

如果您只需要访问字典中的值,您可以这样做:

[Test]
public void TestForWithDictionary()
{
    var dictionary = new Dictionary<string, string>
    {
        { "Graham Greene", "English" },
        { "F. Scott Fitzgerald", "American" }
    };
    Helper.AssertTemplateResult(" English  American ", "{% for item in authors %} {{ item }} {% endfor %}",
        Hash.FromAnonymousObject(new { authors = dictionary.Values }));
}

但是,如果您确实需要访问 for 循环内的键和值,那么 DotLiquid 的当前版本 (1.6.1) 不支持此功能。

【讨论】:

    【解决方案2】:

    只需为字典对象创建一个drop。然后用它来包装你的成员,这些成员是你的 drop 中的字典。即:

    public class MyDictionaryDrop : Drop
    {
        private Dictionary<string,string> _myDictionary;
        public DictionaryDrop<string, string> MyDictionary
        {
            get 
            { 
                return new DictionaryDrop<string, string>(_myDictionary);  
            }
        }
    }
    
    public class DictionaryDrop<TKey,TValue> : Drop ,IEnumerable
    {
        private readonly Dictionary<TKey, TValue> _dictionary;
        public DictionaryDrop(Dictionary<TKey,TValue> dictionary)
        {
            _dictionary = dictionary;
        }
    
        public ICollection<TKey> Keys { get { return _dictionary.Keys; } }
        public ICollection<TValue> Values { get { return _dictionary.Values; } }
        public TValue this[TKey key] { get { return _dictionary[key]; } }
    
        public IEnumerator GetEnumerator()
        {
            return _dictionary.GetEnumerator();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2015-03-07
      • 2020-12-15
      • 2013-04-29
      • 2013-04-20
      • 1970-01-01
      相关资源
      最近更新 更多