字典<tkey,tvalue =“”>。ForEach方法

时间:2015-12-22 13:24:46

标签: c#

我想申报类似于List.ForEach Method的新扩展方法。

我想归档的内容:

var dict = new Dictionary<string, string>()
{
   { "K1", "V1" },
   { "K2", "V2" },
   { "K3", "V3" },
};


dict.ForEach((x, y) => 
{
   Console.WriteLine($"(Key: {x}, value: {y})");
});

我该怎么做?

4 个答案:

答案 0 :(得分:3)

尝试以下方法:

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 :(得分:3)

您可以轻松编写扩展方法:

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

答案 2 :(得分:1)

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);
    }
}

答案 3 :(得分:1)

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})"));