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 }
  • 相关阅读:
    jvm系列(八):jvm知识点总览-高级Java工程师面试必备
    jvm系列(七):jvm调优-工具篇
    JVM学习(2)——技术文章里常说的堆,栈,堆栈到底是什么,从os的角度总结
    Java ClassLoader详解
    语言堆栈入门——堆和栈的区别
    kubernetes基本了解
    软编码和硬编码的理解
    前台页面传日期类型后台接收问题
    mybatis-plus简单了解
    二叉树基础知识
  • 原文地址:https://www.cnblogs.com/ants_double/p/5365002.html
Copyright © 2011-2022 走看看