How to convert a List as comma separated string using Linq, C#

Here I am resolving the problem with different approaches using C#


        

   static void Main(string[] args)
        {
            ListCommaSepearted();
        }

        public static void ListCommaSepearted()
        {

            List lstString = new List()
              {
                  "Coder",
                  "Juggernaut",
                  "Blog"
              };

            // Method 1
            var k = "";
            foreach (var item in lstString)
            {
                k = k+ item + ",";
            }
            k= k.Remove(k.LastIndexOf(','));
            
            // Method 2

            var str = string.Join(",",lstString);
            var q = "";
 
            //Method 3
            lstString.ForEach(delegate(string item)
            {
                q = q + item + ",";
            });

            //Method 4
            var p = "";
            lstString.ForEach(x =>
            {
                p = p + x + ",";
            });

            Console.WriteLine("Coma : {0} ", p);
            Console.ReadLine();
        }

0 comments: