Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: .NET
Expertise: Beginner
Jul 13, 2009

Converting Between List and String Types

These handy functions let you easily convert from a generic string List to a delimited string, or from a delimited string to a string List:

/// <summary>
/// Converts List to string with given separator.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="separator">The separator.</param>
/// <returns></returns>
public static string ListToString(
   List<string> list,string separator)
{
   StringBuilder sb = new StringBuilder();
   foreach (string s in list)
   {
      sb.Append(string.Format("{0}{1}", s, separator));
   }
   string returnString = string.Empty; ;
   //Remove the last separator from the list
   if (sb.Length > 0)
   {
      returnString = sb.Remove(
         sb.ToString().LastIndexOf(separator), 
         separator.Length).ToString();
   }
   return returnString;
}

/// <summary>
/// Strings to string list.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="separator">The separator.</param>
/// <returns></returns>
public static List<string> StringToStringList(string items, char separator)
{
      List<string> list = new List<string>();
      string[] listItmes = items.Split(separator);
      foreach (string item in listItmes)
      {
          list.Add(item);
      }
      if (list.Count > 0)
          return list;
      else
          return null;
}
Srinath MS
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap