只在循环的第一次迭代中添加值
本文关键字:添加 迭代 第一次 循环 | 更新日期: 2023-09-27 18:11:42
我使用以下代码,我需要连接键和值,但编辑属性应该添加到字符串只是在开始(只是在第一次),我该怎么做?我试图找到当前和列表的索引,但没有成功…任何想法?
string Meassage = null;
foreach (var current in PropList)
{
Meassage = "edit:" + current.Key + "=" + current.Value;
}
将键值对列表写入循环中的Message
,然后在末尾将"edit:"
前置,如下所示:
foreach (var current in PropList) {
Message += current.Key + "=" + current.Value + " ";
}
Message = "edit:" + Message;
注意,这是不是一个有效的方法:而不是附加值到string
,您可以使用StringBuilder
或string.Join
方法:
Message = "edit:" + string.Join(" ", PropList.Select(current => current.Key + "=" + current.Value));
使用LINQ的另一种方法是在PropList
上运行Aggregate
(假设这是一个与LINQ兼容的集合类型):
string message = PropList.Count > 0
? PropList.Aggregate("edit:", (agg, current) => agg + current.Key + "=" + current.Value)
: null;
当考虑到性能/内存使用时,使用StringBuilder
来减少内存分配的数量也是一个好主意,但我想这不是这里需要的想法。
为了完整起见,您也可以使用StringBuilder
来完成上述操作,我个人喜欢简洁:
string message = PropList.Count > 0
? PropList.Aggregate(new StringBuilder("edit:"),
(builder, current) => builder.Append(current.Key).Append("=").Append(current.Value)).ToString()
: null;
var Proplist = new Dictionary<int, string>();
Proplist.Add(1, "test1");
Proplist.Add(2, "test2");
var first = Proplist.First();
int key = first.Key;
string Message = null;
foreach (var current in Proplist)
{
if (first.Key == current.Key)
{
//do only one
}
else
{
Message = "edit:" + current.Key + "=" + current.Value;
}
}