Converting Between List and String Types

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:

/// /// Converts List to string with given separator./// /// The list./// The separator./// public static string ListToString(   List 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;}/// /// Strings to string list./// /// The items./// The separator./// public static List StringToStringList(string items, char separator){      List list = new List();      string[] listItmes = items.Split(separator);      foreach (string item in listItmes)      {          list.Add(item);      }      if (list.Count > 0)          return list;      else          return null;}


Share the Post: