Skip to main content
 首页 » 编程设计

c#之使用 Lambda 表达式遍历键值对的通用列表

2024年02月23日13zhoujg

我是 Lambda 表达式的新手,所以已经试验了一个小时。

我有一个通用列表 - List<KeyValuePair<int, string>> 基本上拿着一把 key

和一个值对。我正在寻找使用 lambda 表达式打印列表项。任何人都可以

帮助我使用 Lambda 表达式翻译以下 foreach 语句?

foreach(KeyValuePair<int, string> kvp in list) 
{ 
    Console.WriteLine(kvp.Key.ToString() + " ----> " + kvp.Value.ToString()); 
} 

请您参考如下方法:

通过通用 Converter(TInput, TOutput) 委托(delegate)封装 LINQ 表达式:

Converter<List<KeyValuePair<int, string>>, string> converter = (input) => 
    { 
        return input.Select(i => i.Key + " --> " + i.Value) 
                    .Aggregate((a, n) => a + Environment.NewLine + n); 
    }; 

用法:

string output = converter(items); 

测试数据集:

var items = new List<KeyValuePair<int, string>> 
    { 
            new KeyValuePair<int, string>(1, "111"), 
            new KeyValuePair<int, string>(2, "222"), 
            new KeyValuePair<int, string>(3, "333"), 
    }; 

输出:

1 --> 111 
2 --> 222 
3 --> 333