• 使Dictionary泛型查询简单化


    我们经常使用Dictionary<T> 来做些操作,查询一个object,没有找到就Add它。代码像如样:

       1:  private static Dictionary<string,Employee> employees;
       2:  
       3:  public static Employee GetByName(string name) {
       4:      Employee employee;
       5:      if (!employees.TryGetValue(name, out employee)) {
       6:          employee = new Employee(whatever);
       7:          employees.Add(name, employee);
       8:      }
       9:      return employee;
      10:  }

    现在我们写个扩展方法:

            /// <summary>
            /// Gets the or add.
            /// </summary>
            /// <typeparam name="TKey">The type of the key.</typeparam>
            /// <typeparam name="TDictionaryValue">The type of the dictionary value.</typeparam>
            /// <typeparam name="TActualValue">The type of the actual value.</typeparam>
            /// <param name="dictionary">The dictionary.</param>
            /// <param name="key">The key.</param>
            /// <param name="newValue">The new value.</param>
            /// <returns>TActualValue</returns>
            public static TActualValue GetOrAdd<TKey, TDictionaryValue, TActualValue>(this IDictionary<TKey, TDictionaryValue> dictionary,
        TKey key, Func<TActualValue> newValue) where TActualValue : TDictionaryValue
            {
                TDictionaryValue value;
                if (!dictionary.TryGetValue(key, out value))
                {
                    value = newValue.Invoke();
                    dictionary.Add(key, value);
                }
                return (TActualValue)value;
            }

    一个HelpMethod:

       1:          public static Employee GetByName(string name)
       2:          {
       3:              return employees.GetOrAdd(name, () => new Employee(){Name=name});
       4:          }

    最后看Test,简化了:

       1:          [Test]
       2:          public void TestDic()
       3:          {
       4:              employees = new Dictionary<string, Employee>();
       5:              var emp=GetByName("Petter");
       6:              Assert.AreEqual("Petter", emp.Name);
       7:              Assert.IsInstanceOf(typeof(Employee), emp);
       8:          }

    Employee这个Class用于演示,您可以随意创建,或是其他Object。希望这篇Post对你有帮助.

    Author: Petter Liu    http://wintersun.cnblogs.com

  • 相关阅读:
    bash 常用操作
    阿里云专有网络与弹性公网IP
    Excel 中 Index 和 Match 方法的使用
    分割excel sheet
    vba 工作案例-sheet间拷贝内容
    趣味题:重男轻女的村庄
    vba 工作案例1
    wordpress 导航相关的函数
    怎么样打印加密PDF文件
    excel 2013 图表制作
  • 原文地址:https://www.cnblogs.com/wintersun/p/1556021.html
Copyright © 2020-2023  润新知