CSharp examples for System.Collections:IEnumerable
Builds a string representation for IEnumerable
using System.Text; using System.Collections.Generic; using System.Collections; using System;/*from w ww.jav a 2 s . c o m*/ public class Main{ /// <summary> /// Builds a string reprensentation for a <paramref name="collection"/> /// </summary> /// <param name="collection"></param> /// <param name="seperator">the string used to seperate strings of different items</param> /// <returns>returns <see cref="String.Empty"/> if the <paramref name="collection"/> is empty.</returns> /// <remarks> /// Note that item with an empty ToString() won't show up in this representation. /// To control this behavior use <see cref="ToString(IEnumerable , string , string , string ) "/> /// </remarks> public static string ToString(IEnumerable collection, string seperator) { return ToString(collection, seperator, string.Empty); } /// <summary> /// Builds a string reprensentation for a <paramref name="collection"/> /// </summary> /// <param name="collection"></param> /// <param name="seperator">the string used to seperate strings of different items</param> /// <param name="emptyText">the string to be return if the <paramref name="collection"/> is empty</param> /// <param name="nullText">the string to use when the item is null or its ToString() returns an empty string</param> /// <returns></returns> public static string ToString(IEnumerable collection, string seperator, string emptyText, string nullText) { StringBuilder sb = new StringBuilder(); foreach (object o in collection) { string s = string.Empty; if (o != null) s = o.ToString(); if (string.IsNullOrEmpty(s)) s = nullText; if (!string.IsNullOrEmpty(s)) sb.Append(s + seperator); } if (sb.Length > 0) { sb.Remove(sb.Length - seperator.Length, seperator.Length); return sb.ToString(); } else return emptyText; } /// <summary> /// Builds a string reprensentation for a <paramref name="collection"/> /// </summary> /// <param name="collection"></param> /// <param name="seperator">the string used to seperate strings of different items</param> /// <param name="emptyText">the string to be return if the <paramref name="collection"/> is empty</param> /// <returns></returns> /// <remarks> /// Note that null tiems and items with an empty ToString() won't show up in this representation /// To control this behavior use <see cref="ToString(IEnumerable , string , string , string ) "/> /// </remarks> public static string ToString(IEnumerable collection, string seperator, string emptyText) { return ToString(collection, seperator, emptyText, string.Empty); } }