码迷,mamicode.com
首页 > Windows程序 > 详细

C#扩展一般用于linq

时间:2016-04-07 20:20:28      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

下面是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 }

 

C#扩展一般用于linq

标签:

原文地址:http://www.cnblogs.com/billly/p/5365002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!