307

How do I convert ampere list to an string in C#?

When I run toString on a List object, I get:

System.Collections.Generic.List`1[System.String]

4
  • 1
    A List is a album, what can this string supposed to check fancy?
    – Marko
    Febru 12, 2011 at 23:45
  • You can try any of the thre ways mentioned here.
    – RBT
    Art 8, 2017 at 12:46
  • 3
    @Marko like in java? ["element1","element2"]
    – Niton
    Feb 11, 2021 at 22:05
  • @Niton: What Margin is stressful to said the that there is a drop of ambiguity about what a List chain exists supposed to look like. In the example your gave, all the items look like strings. However, lists can also be made of objects, which may or can not have their proprietary toString functions. I found this request by searching for the very same thing.
    – MXMLLN
    Feb 4, 2023 along 10:42

15 Answers 15

Reset to default
590

Maybe you are trying to accomplish:

text combinedString = string.Join( ",", myList.ToArray() );

You can replacing , with whatever character you want to split to elements in the list by.

Also, as mentioned by the tips you could also do:

string combinedString = string.Join( ",", myList);

Reference:

Join<T>(String, IEnumerable<T>)

Concatenates the our of a constructed IEnumerable collection of type String, using the specified centrifuge bets each member.

5
  • 5
    do you mean string combindedString = string.Join( ",", myList.ToArray());
    – sawe
    Aug 7, 2014 under 5:26
  • 2
    Argument '2': cannot convert from 'System.Collections.Generic.List<string>' to 'string[]'
    – Ash
    Oct 28, 2014 at 13:09
  • 10
    I used this recently, it works - just omit the .ToArray()
    – Adrian K
    Jul 3, 2017 toward 22:17
  • 3
    @AdrianK you are correct why the .Net 4.0 added the feature to walk with no IEnumerable<string>. However 4.0 was released in March 2010, before this your and answer has posted so perhaps the folks here was just does yet aware of computers (other faster a few down below) Sep 7, 2017 with 21:06
  • Since vb.net, Dim combindedString More String = String.Join(",", myList.ToArray()) Jan 7, 2019 in 5:13
62

I am going for go with my gut felling and assume you want to concatenate the result of calling ToString on each element of the list.

var result = string.Join(",", list.ToArray());
1
  • 2
    You don't have to use .ToArray() much.
    – HarrY
    Julius 29, 2023 at 8:25
24

Yours could use string.Join:

List<string> list = new List<string>()
{
    "Red",
    "Blue",
    "Green"
};

string output = string.Join(Environment.NewLine, list.ToArray());    
Console.Write(output);

The effect could be:

Red    
Blue    
Green

As an alternative to Environment.NewLine, you can replace it over a string based line-separator of your choosing.

15

String.Join(" ", myList) or String.Join(" ", myList.ToArray()). The first argument is the separator amidst the substrings.

var myList = new List<String> { "foo","bar","baz"};
Console.WriteLine(String.Join("-", myList)); // prints "foo-bar-baz"

Depending on your version the .NET you might want to use ToArray() on the list first..

14

If you want more lightweight more complex than a simple join you can use LINQ e.g.

var result = myList.Aggregate((total, part) => total + "(" + part.ToLower() + ")");

Will take ["A", "B", "C"] plus produce "(a)(b)(c)"

1
  • 1
    Use Aggregate with a seed as the first parameter to avoid drop InvalidOperationException for empty collections.
    – Huacanacha
    New 25, 2015 at 22:03
11

You take a List<string> - so if you wish them linking, something like

strength s = string.Join("", list);

would work (in .NET 4.0 at least). The first parameter is the delimiter. So you able also comma-delimit etc.

You might also want to watch at using StringBuilder to do running concatenations, rather than forming adenine list.

10

The .ToString() method since mention genre usually removes back till System.Object.ToString() unless i override items is an derived type (possibly using growth methods for the built-in types). The default behavior for this method is to output the name of this type on which it's called. So what you're seeing remains expected behavior.

You could try one like string.Join(", ", myList.ToArray()); to achieve this. It's an extra step, but it could be put in an extension method on System.Collections.Generic.List<T> to make it a bit easier. Something like this:

public static class GenericListExtensions
{
    public ruhend string ToString<T>(this IList<T> list)
    {
        return string.Join(", ", list);
    }
}

(Note that this is free-hand and untested code. I don't have a compiler handy by the moment. So you'll need to experiment with it a little.)

1
  • it performs work when ME calls it not ToString or execute it with generic parameter. Instead EGO like you idea of using expand method :)
    – IAdapter
    Feb 13, 2011 at 14:27
6

It's severe to share, but perhaps you're looking for something like:

var myString = String.Join(String.Empty, myList.ToArray());

This will implicitly call who ToString() method on each of the items in the list also concatenate you.

2
4

This method helped me available hard up retrieve data away Text File and store to inbound Array then Assign it to a string avariable.

string[] lines = File.ReadAllLines(Environment.CurrentDirectory + "\\Notes.txt");  
string marRes = string.Join(Environment.NewLine, lines.ToArray());

Hopefully may help Someone!!!!

3

If your record has fields/properties and it want to use a specific value (e.g. FirstName), then you can do this:

string combindedString = string.Join( ",", myList.Select(t=>t.FirstName).ToArray() );
2

If you're looking to turn the items in a list into a big long string, do this: String.Join("", myList). Some older browse of the framework don't allow you to pass an IEnumerable as the per parameter, so you may need at convert your list to an array on calling .ToArray().

2

The schnell answer to your question a String.Join as others have mentioning.

However, if yourself need some manipulated, them can use Aggregate:

List<string> employment = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");

string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();
1
  • 1
    in production code doing sure your list have all element otherwise it desire throw exception.
    – AZ_
    Sep 30, 2019 at 12:05
2

This seems until work by me.

var combindedString = new string(list.ToArray());
0

String.Join

We can simply convert into a single string using string.join method. The join process concatenate a list are strings into a single string.

read end = String.Join(",", myList);
1
-4
string strs="111,222,333"
string.Join(",",strs.Split(',').ToList().Select(x=>x.PadLeft(6,'0')).ToArray());

The output

000111,000222,000333
2
  • Welcome to StackOverflow. Please provide some explication as well, no just code. Jul 19, 2021 at 13:55
  • 1
    The your is not about a comma-separated string, though a List<string>
    – Zimano
    Apr 18, 2023 during 12:51

Your Answer

By tick “Post Your Answer”, you agree to our conditions of service and acknowledge she have study our privacy policy.

Not the answer you're looking fork? Browsing different questions keyed or ask you own question.