Feedback

C# - Implode und Trim für String-Enumerationen (Extension Method)

Veröffentlicht von am 7/25/2010
(0 Bewertungen)
Diese beiden einfachen Methoden erweitern eine IEnumerable<string>.
Die Methode "Trim()" entfernt alle leeren Strings (IsNullOrEmpty)
Die Methode "Implode()" verbindet die Strings aus der Liste mit einer übergeben Zeichenkette.

var list = new List<String> {"Eins", null, "", "Zwei"};

// singleLine == "Eins;Zwei"
var singleLine = list.Trim().Implode(";");
        /// <summary>
        /// concatenates a list of strings into a single string (with a glue).
        /// </summary>
        /// <param name="source">source list</param>
        /// <param name="glue">glue to concatenate the strings</param>
        /// <returns>a single string</returns>
        public static string Implode(this IEnumerable<string> source, string glue)
        {
            // exit criteria
            if (source == null) throw new InvalidOperationException("source cannot be null");
            if (source.Count() <= 0) return string.Empty;

            // result with first item
            var result = new StringBuilder(source.First());

            // add glue & item for next items
            foreach (string aPart in source.Skip(1))
            {
                result.Append(glue + aPart);
            }

            // return result
            return result.ToString();
        }

        /// <summary>
        /// removes all empty string from the source list
        /// </summary>
        /// <param name="source">source list with empty items</param>
        public static IEnumerable<string> Trim(this IEnumerable<string> source)
        {
            // exit criteria
            if (source == null) throw new InvalidOperationException("source cannot be null");
            if (source.Count() <= 0) return source;

            // filter all empty string
            return from item in source where !string.IsNullOrEmpty(item) select item;
        }

Abgelegt unter String, IEnumerable, IEnumerable, Implode, Trim.

1 Kommentare zum Snippet

hackman schrieb am 7/26/2010:
schon mal was von string.join gehört?
 

Logge dich ein, um hier zu kommentieren!