zoukankan      html  css  js  c++  java
  • C#扩展一般用于linq

    下面是dictionary的扩展

     1 using System.Collections.Generic;
     2 
     3 namespace NetAnalysis.Common
     4 {
     5 
     6   public static class DictionaryExtensionMethodClass
     7     {
     8         /// <summary>
     9         /// 尝试将键和值添加到字典中:如果不存在,才添加;存在,不添加也不抛导常
    10         /// </summary>
    11         public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
    12         {
    13             if (dict.ContainsKey(key) == false)
    14                 dict.Add(key, value);
    15             return dict;
    16         }
    17 
    18 
    19         /// <summary>
    20         /// 将键和值添加或替换到字典中:如果不存在,则添加;存在,则替换
    21         /// </summary>
    22         public static Dictionary<TKey, TValue> AddOrPeplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
    23         {
    24             dict[key] = value;
    25             return dict;
    26         }
    27 
    28         /// <summary>
    29         /// 获取与指定的键相关联的值,如果没有则返回输入的默认值
    30         /// </summary>
    31         public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
    32         {
    33             return dict.ContainsKey(key) ? dict[key] : defaultValue;
    34         }
    35 
    36         /// <summary>
    37         /// 向字典中批量添加键值对
    38         /// </summary>
    39         /// <param name="replaceExisted">如果已存在,是否替换</param>
    40         public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
    41         {
    42             foreach (var item in values)
    43             {
    44                 if (dict.ContainsKey(item.Key) == false || replaceExisted)
    45                     dict[item.Key] = item.Value;
    46             }
    47             return dict;
    48 
    49         }
    50   
    51   }
    52 }
  • 相关阅读:
    设计模式之责任链模式(Chain of Responsibility )
    Cubieboard2裸机开发之(二)板载LED交替闪烁
    Cubieboard2裸机开发之(一)点亮板载LED
    A20(Cubieboard2)启动过程浅析
    入手Cubieboard2之制作最小Linux系统
    ARM Linux启动代码分析
    Linux设备驱动剖析之Input(四)
    Linux设备驱动剖析之Input(三)
    Linux设备驱动剖析之Input(二)
    Linux设备驱动剖析之Input(一)
  • 原文地址:https://www.cnblogs.com/ants_double/p/5365002.html
Copyright © 2011-2022 走看看