0

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

enter image description here

How can I get the formula values and append in the foreach?

2 Answers 2

3

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();
      }
   }
Sign up to request clarification or add additional context in comments.

Comments

3

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('|')); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.