mikemind
mikemind

Reputation: 49

Store list values in a string in c#

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?

Upvotes: 0

Views: 2906

Answers (2)

sujith karivelil
sujith karivelil

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

Mairaj Ahmad
Mairaj Ahmad

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

Related Questions