Say that for debugging purposes, I want to quickly get the contents of an IEnumerable into one-line string with each string item comma-separated. I can do it in a helper method with a foreach loop, but that's neither fun nor brief. Can Linq be used? Some other short-ish way?
In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();
The standard solution to convert a List<string> to a comma-separated string in C# is using the string. Join() method. It concatenates members of the specified collection using the specified delimiter between each item.
In Java, we can use String. join(",", list) to join a List String with commas.
In C#, all collections (eg lists, dictionaries, stacks, queues, etc) are enumerable because they implement the IEnumerable interface. So are strings. You can iterate over a string using a foreach block to get every character in the string.
using System; using System.Collections.Generic; using System.Linq; class C { public static void Main() { var a = new []{ "First", "Second", "Third" }; System.Console.Write(string.Join(",", a)); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With