/// <summary>
/// Dictionary的扩展方法使用
/// </summary>
public static void DicSample4()
{
//1)普通调用
Dictionary< int , String> dict = new Dictionary< int , String>();
DictionaryExtensionMethodClass.TryAdd(dict, 1, "ZhangSan" );
DictionaryExtensionMethodClass.TryAdd(dict, 2, "WangWu" );
DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "WangWu" );
DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "ZhangWu" );
DictionaryExtensionMethodClass.TryAdd(dict, 2, "LiSi" );
//2)TryAdd 和 AddOrReplace 这两个方法具有较强自我描述能力,用起来很省心,而且也简单:
dict.AddOrPeplace(20, "Orange" );
dict.TryAdd(21, "Banana" );
dict.TryAdd(22, "apple" );
//3)像Linq或jQuery一样连起来写
dict.TryAdd(10, "Bob" )
.TryAdd(11, "Tom" )
.AddOrPeplace(12, "Jom" );
//4) 获取值
String F = "Ba" ;
dict.TryGetValue(31, out F);
Console.WriteLine( "F : {0}" ,F);
foreach ( var dic in dict)
{
Console.WriteLine( "Output : Key : {0}, Value : {1}" , dic.Key, dic.Value);
}
//5)下面是使用GetValue获取值
var v1 = dict.GetValue(111, null );
var v2 = dict.GetValue(10, "abc" );
//6)批量添加
var dict1 = new Dictionary< int , int >();
dict1.AddOrPeplace(3, 3);
dict1.AddOrPeplace(5, 5);
var dict2 = new Dictionary< int , int >();
dict2.AddOrPeplace(1, 1);
dict2.AddOrPeplace(4, 4);
dict2.AddRange(dict1, false );
}
|