Join list and single string

Viewed 128

Why this input:

var list = new List<string>()
{
    "a","b","c"
};

var out1 = string.Join(", ", list.Select(t => t));
var out2 = string.Join(", ", list.Select(t => t), "d");

Console.WriteLine("out1 = " + out1);
Console.WriteLine("out2 = " + out2);

gives that output:

out1 = a, b, c
out2 = System.Linq.Enumerable+WhereSelectListIterator`2[System.String,System.String], d

I don't understand why I got:

System.Linq.Enumerable+WhereSelectListIterator`2[System.String,System.String]

in out2. Any ideas?

4 Answers

Your second example is calling this overload:

public static string Join(string? separator, params object?[] values);

So your second and third argument are being passed as an object[] here:

var out2 = string.Join(", ", list.Select(t => t), "d");

string.Join is internally calling ToString() on each item in the array, hence the output.


If you want to append a single string to the list, you could use Enumerable.Append:

var out2 = string.Join(", ", list.Append("d"));

Which would call this overload:

public static string Join(
    string? separator, System.Collections.Generic.IEnumerable<string?> values);

it's because you're using two different overloads of string.Join() in the first one you're using the one which accepts an IEnumerable such as the one you obtain from list.Select(t => t) , the second one the compiler tries to use the one that wants an array of objects as the extra parameters, then it joins the two objects you are passing: the list.Select(t => t) and "d", i guess it uses .ToString() on both, and you get the Type name for the first

You wrote an incorrect call for string.Join. Just create a new list with the d and then call string.Join:

var list = new List<string>()
{
    "a","b","c"
};

var out1 = string.Join(", ", list.Select(t => t));

var listWithD = list.Select(t => t).ToList();
listWithD.Add("d");
var out2 = string.Join(", ", listWithD);

Console.WriteLine("out1 = " + out1);
Console.WriteLine("out2 = " + out2);

And the output will be:

out1 = a, b, c
out2 = a, b, c, d

If you need, here documentation for string.Join.

You get this result because string.Join() in the second case takes an array of arguments, which are separated by commas. You pass the first argument list.Select (t => t), and the second "d". The first one calls ToString() so you get a result like this

Related