2016-12-16 44 views
0

我有一个存储一些字符串值的列表。将列表值存储在c中的字符串中#

代码:

List<VBCode> vbCodes = new List<VBCode>(); 

public class VBCode 
{ 
    public string Formula { get; set; } 
} 

在一个方法,我想追加列表值。像图所示

enter image description here

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追加?

回答

3

要附加的item object您需要使用String.Join()appendobject 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(); 
     } 
    } 
3

你可以这样做只是没有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('|')); 
相关问题