locked
Help creating a helper function... RRS feed

  • Question

  • I'm trying to figure out how to create an extension method for all EntityCollection<T> objects. Specifically, I want to create a method that returns a concatenated string of a specific property of each entity in the collection.

    Something like:

    string concatenatedList = myPersonCollection.ToConcatenatedList( p => p.FirstName );

    That should produce a string like: "Bob, Sue, Fred". I'm not quite sure how to go about doing this. Any ideas?
    Wednesday, August 20, 2008 8:21 PM

Answers

  • I think, simple Select() combined with String.Join() will do the trick and can work on top of any IEnumerable<T>:

     

    Code Snippet

    public static string ToConcatenatedList<T>(this IEnumerable<T> list, Func<T, string> selector, string separator)

    {

        return String.Join(separator, list.Select(selector).ToArray());

    }

    public static string ToConcatenatedList<T>(this IEnumerable<T> list, Func<T, string> selector)

    {

        return list.ToConcatenatedList(selector, ",");

    }

     

     

     

    Thursday, August 21, 2008 12:45 AM

All replies

  • I think, simple Select() combined with String.Join() will do the trick and can work on top of any IEnumerable<T>:

     

    Code Snippet

    public static string ToConcatenatedList<T>(this IEnumerable<T> list, Func<T, string> selector, string separator)

    {

        return String.Join(separator, list.Select(selector).ToArray());

    }

    public static string ToConcatenatedList<T>(this IEnumerable<T> list, Func<T, string> selector)

    {

        return list.ToConcatenatedList(selector, ",");

    }

     

     

     

    Thursday, August 21, 2008 12:45 AM
  • Excellent, thank you. I'm getting fairly comfortable using lambdas, but I stumble a bit writing them still.
    Thursday, August 21, 2008 3:12 AM