c# - 一种简化提供的代码的优雅方式

标签 c# string list

假设有一个列表:

var rawItems = new List<KeyValuePair<string, string>>()
{
    new KeyValuePair<string,string>("A", "1"),
    new KeyValuePair<string,string>("B", "2"),
    new KeyValuePair<string,string>("C", "3")
};

并且需要构造一个字符串int,形式如下:

A = 1,
B = 2,
C = 3

正在使用的方法:

List<string> transformedItems = new List<string>();
rawItems.ForEach(item => transformedItems.Add(item.Key + " = " + item.Value));
string result = String.Join("," + Environment.NewLine, transformedItems.ToArray());

如果有人能想到一种更优雅的方式来做到这一点,我会很高兴。

P.S.:不一定是“同一行代码”类型的解决方案,而是另一种方式。

最佳答案

也许你会发现这个“优雅”:

var result = string.Join(",\r\n", rawItems.Select(
                                  x => string.Format("{0} = {1}", x.Key, x.Value)));

关于c# - 一种简化提供的代码的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31203192/

相关文章:

c# - 优化 LINQ 查询

javascript - 在不改变词序的情况下反转字符串中的每个词

python - 如何比较列表中连续整数的最后一位数字?

c# - 从通用列表中查找符合任何条件的项目

C# Skype API 视频通话

c# - 丢弃异常变量时是否存在技术差异?

c# - 尝试在字符串中查找单个字符的更快方法是什么?

regex - 删除一定长度的单词之间的空格

python - 在 Python 中编辑列表内容

python - 可以做更多的pythonic吗?