स्ट्रिंग की एक लिस्ट को बिल्ट-इन string.Join एक्सटेंशन मेथड का उपयोग करके कॉमा-सेपरेटेड स्ट्रिंग में परिवर्तित किया जा सकता है।
string.Join(",", list);
इस प्रकार का रूपांतरण वास्तव में उपयोगी होता है जब हम यूज़र से डेटा की एक लिस्ट एकत्र करते हैं (उदाहरण: चेकबॉक्स चयनित डेटा) और इसे कॉमा-सेपरेटेड स्ट्रिंग में परिवर्तित करते हैं और आगे प्रोसेस करने के लिए डेटाबेस को क्वेरी करते हैं।
उदाहरण
using System;
using System.Collections.Generic;
namespace DemoApplication
{
public class Program
{
static void Main(string[] args)
{
List fruitsList = new List { "banana", "apple", "mango" };
string fruits = string.Join(",", fruitsList);
Console.WriteLine(fruits);
Console.ReadLine();
}
}
}
आउटपुट
banana,apple,mango
इसी तरह, कॉम्प्लेक्स ऑब्जेक्ट्स की लिस्ट में एक प्रॉपर्टी को भी नीचे की तरह कॉमा-सेपरेटेड स्ट्रिंग में परिवर्तित किया जा सकता है।
उदाहरण - कॉम्प्लेक्स ऑब्जेक्ट्स
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication
{
public class Program
{
static void Main(string[] args)
{
var studentsList = new List
{
new Student { Id = 1, Name = "John" },
new Student { Id = 2, Name = "Jack" }
};
string students = string.Join(",", studentsList.Select(student => student.Name));
Console.WriteLine(students);
Console.ReadLine();
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
}
आउटपुट
John,Jack