词典<;TKey、T值>;.ForEach方法
本文关键字:ForEach gt 方法 lt TKey 词典 | 更新日期: 2023-09-27 18:27:41
我想声明一个新的扩展方法,类似于List.ForEach方法。
我想要归档的内容:
var dict = new Dictionary<string, string>()
{
{ "K1", "V1" },
{ "K2", "V2" },
{ "K3", "V3" },
};
dict.ForEach((x, y) =>
{
Console.WriteLine($"(Key: {x}, value: {y})");
});
我该怎么做?
您可以轻松地编写一个扩展方法:
public static class LinqExtensions
{
public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, Action<TKey, TValue> invoke)
{
foreach(var kvp in dictionary)
invoke(kvp.Key, kvp.Value);
}
}
像这样使用:
dict.ForEach((x, y) =>
{
Console.WriteLine($"(Key: {x}, value: {y})");
});
生成
Key: K1, value: V1
Key: K2, value: V2
Key: K3, value: V3
尝试以下操作:
var dict = new Dictionary<string, string>()
{
{ "K1", "V1" },
{ "K2", "V2" },
{ "K3", "V3" },
};
foreach(KeyValuePair<string, string> myData in dict )
{
// Do something with myData.Value or myData.Key
}
这就是扩展方法:
public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, Action<TKey, TValue> invokeMe)
{
foreach(var keyValue in dictionary)
{
invokeMe(keyValue.Key, keyValue.Value);
}
}
1:扩展方法必须在非嵌套、非泛型的静态类中声明
2:第一个参数必须使用this
关键字进行注释。
public static class DictionaryExtensions
{
public static void ForEach<TKey, TValue>(
this Dictionary<TKey, TValue> dictionary,
Action<TKey, TValue> action) {
foreach (KeyValuePair<TKey, TValue> pair in dictionary) {
action(pair.Key, pair.Value);
}
}
}
然后可以像调用常规实例方法一样调用此方法:
dict.ForEach((key, value) =>
Console.WriteLine($"(Key: {key}, Value: {value})"));
var dic = new Dictionary<string, string>();
dic.Add("hello", "bob");
dic.Foreach(x =>
{
Console.WriteLine(x.Key + x.Value);
});
public static void Foreach<T, TY>(this Dictionary<T, TY> collection, Action<T, TY> action)
{
foreach (var kvp in collection)
{
action.Invoke(kvp.Key, kvp.Value);
}
}