Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join list and single string

Tags:

c#

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?

like image 955
dafie Avatar asked Mar 23 '26 20:03

dafie


2 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);
like image 113
Johnathan Barclay Avatar answered Mar 26 '26 10:03

Johnathan Barclay


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

like image 31
Mattia Mele Avatar answered Mar 26 '26 08:03

Mattia Mele