[英]Store list values in a string in c#
我有一個存儲一些字符串值的列表。
碼:
List<VBCode> vbCodes = new List<VBCode>();
public class VBCode
{
public string Formula { get; set; }
}
在一種方法中,我嘗試附加列表值。
public void ListValue()
{
if (vbCodes.Count > 0)
{
StringBuilder strBuilder = new StringBuilder();
foreach (var item in vbCodes)
{
strBuilder.Append(item).Append(" || ");
}
string strFuntionResult = strBuilder.ToString();
}
}
該列表將具有如下所示的值
如何獲取公式值並將其附加在foreach中?
您要追加item object
您需要append
object property Formula
public void ListValue()
{
if (vbCodes.Count > 0)
{
StringBuilder strBuilder = new StringBuilder();
foreach (var item in vbCodes)
{
strBuilder.Append(item.Formula).Append(" || ");
}
string strFuntionResult = strBuilder.ToString();
}
}
您可以使用String.Join()
來簡單地執行此操作而無需foreach
,就像這樣:
string strFuntionResult = String.Join(" || ", vbCodes.Select(x=>x.Formula).ToList());
如果您真的想使用foreach進行迭代,則意味着必須從迭代器變量中獲取Formula
,還應注意刪除最終的||
完成迭代后,如果是這樣,代碼將如下所示:
StringBuilder strBuilder = new StringBuilder();
foreach (var item in vbCodes)
{
strBuilder.Append(item.Formula).Append(" || ");
}
string strFuntionResult = strBuilder.ToString(); // extra || will be at the end
// To remove that you have to Trim those characters
// or take substring till that
strFuntionResult = strFuntionResult.Substring(0, strFuntionResult.LastIndexOf('|'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.