Convert genetic List to comma separated string enclosed within quotes using C# and VB.Net

Last Reply on Oct 31, 2014 02:48 AM By Azim

Posted on Oct 31, 2014 02:48 AM

Hello friends, I am looking for a way to format a generic list<string>,

List<string> list1 = new List<string>();
 
I was trying with the following code
string allProductId = string.Join(",", list);

but I can get a format like

'option1','option2','option3'

for later use in a query Where In
 
my result,
 
option1,option2,option3
 
but I need the string with single quotes.
 
 
thanks for everything.
Posted on Oct 31, 2014 02:48 AM Modified on on Nov 01, 2014 12:46 AM

You need to use the foreach loop.

C#

protected void Page_Load(object sender, EventArgs e)
{
    List<string> list1 = new List<string>();
    list1.Add("option1");
    list1.Add("option2");
    list1.Add("option3");
    string allProductId = "";
    foreach (string s in list1)
    {
        allProductId += "'" + s + "', ";
    }
    allProductId = allProductId.Remove(allProductId.Length - 2);
}

VB.Net

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    Dim list1 As New List(Of String)()
    list1.Add("option1")
    list1.Add("option2")
    list1.Add("option3")
    Dim allProductId As String = ""
    For Each s As String In list1
        allProductId += (Convert.ToString("'") & s) + "', "
    Next
    allProductId = allProductId.Remove(allProductId.Length - 2)
End Sub