Paul
Paul

Reputation: 26650

LINQ for untyped IEnumerable

I am getting the e object via Reflection and then, if it is an IEnumerable, dump it to string:

public static string EnumerableToString(this IEnumerable e, string separator)
{
    List<string> list = new List<string>();
    foreach (object item in e)
        list.Add($"\"{item}\"");
    return "[" + string.Join(separator, list) + "]";
}

I wonder whether there is a more compact way to do this with LINQ. The Select method of LINQ is only applicable to IEnumerable<T>, not IEnumerable.

Upvotes: 0

Views: 164

Answers (1)

Anton Komyshan
Anton Komyshan

Reputation: 1571

You can use OfType method:

public static string EnumerableToString(this IEnumerable e, string separator)
{
    return $"[{string.Join(separator, e.OfType<object>().Select(x => $"\"{x}\""))}]";
}

Upvotes: 2

Related Questions