Reputation: 49
I have a list which stores some string values.
Code:
List<VBCode> vbCodes = new List<VBCode>();
public class VBCode
{
public string Formula { get; set; }
}
In a method I am trying to append the list values.
public void ListValue()
{
if (vbCodes.Count > 0)
{
StringBuilder strBuilder = new StringBuilder();
foreach (var item in vbCodes)
{
strBuilder.Append(item).Append(" || ");
}
string strFuntionResult = strBuilder.ToString();
}
}
The list will have values like shown below
How can I get the formula values and append in the foreach?
Upvotes: 0
Views: 2906
Reputation: 29006
You can do this simply without foreach
by using String.Join()
, it will be like this :
string strFuntionResult = String.Join(" || ", vbCodes.Select(x=>x.Formula).ToList());
If you really want to iterate using foreach means you have to get Formula
from the iterator variable also take care to remove the final ||
after completing the iteration, if so the code would be like the following:
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('|'));
Upvotes: 3
Reputation: 14604
You are appending the item object
you need to append
the 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();
}
}
Upvotes: 3