Created
January 31, 2019 09:00
-
-
Save binary4cat/1da9df0fa9b885f0a65caab1b32002d9 to your computer and use it in GitHub Desktop.
c# Dictionary 相关扩展
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using System.Collections.Specialized; | |
namespace iCTR.WeiXin.Common.Extensions | |
{ | |
/// <summary> | |
/// 字典类扩展 | |
/// </summary> | |
public static class DictionaryExtend | |
{ | |
/// <summary> | |
/// 根据OrderedDictionary类型的value获取key | |
/// </summary> | |
/// <typeparam name="T1">key的类型</typeparam> | |
/// <typeparam name="T2">value的类型</typeparam> | |
/// <param name="od">OrderedDictionary对象</param> | |
/// <param name="value">value</param> | |
/// <returns>key的值,如果没有则返回零值</returns> | |
public static T1 GetKeyByValue<T1,T2>(this OrderedDictionary od, T2 value) | |
{ | |
foreach (DictionaryEntry o in od) | |
{ | |
// 比较两个参数是否相等 | |
if (EqualityComparer<T2>.Default.Equals((T2)o.Value,value)) | |
{ | |
return (T1) o.Key; | |
} | |
} | |
return default(T1); | |
} | |
/// <summary> | |
/// 根据索引获取字典的一项 | |
/// </summary> | |
/// <param name="od">有序字典</param> | |
/// <param name="i">索引</param> | |
/// <returns>字典项</returns> | |
public static DictionaryEntry GetItemByIndex(this OrderedDictionary od, int i) | |
{ | |
var j = 0; | |
foreach (DictionaryEntry entry in od) | |
{ | |
if (i == j++) | |
{ | |
return entry; | |
} | |
} | |
return new DictionaryEntry(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment